使用WPF内置的路由事件

如下图所示,按照传统的事件做法,会直接将事件和事件的处理器直接绑定到一起,而且需要分别为Left和Right两个按钮关联单击事件的事件处理程序。但使用WPF则没有这样麻烦。


XAML代码如下:
<Window x:Class="Demo001.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="200">
    <Grid x:Name="GridRoot" Background="Lime">
        <Grid x:Name="GridA" Margin="10" Background="Blue">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Canvas x:Name="LeftCanvas" Grid.Column="0" Grid.Row="0" Background="Red" Margin="10">
                <Button x:Name="LeftButton" Content="Left" Width="40" Height="100" Margin="10" />
            </Canvas>
            <Canvas x:Name="RightCanvas" Grid.Column="1" Grid.Row="0" Background="Yellow" Margin="10">
                <Button x:Name="RightButton" Content="Right" Width="40" Height="100" Margin="10" />
            </Canvas>
        </Grid>
    </Grid>
</Window>

为WPF订阅事件处理器则不需要分别为两个按钮订阅,而只需要给它的父级订阅路由事件即可,代码如下:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.GridRoot.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.ButtonClicked));
    }


    void ButtonClicked(object sender, RoutedEventArgs e)
    {
        MessageBox.Show((e.OriginalSource as FrameworkElement).Name);
    }
}

很明显,上面的代码是在GirdRoot这个表格元素上侦听了按钮的单击事件,这样,当包含在它里面的按钮一旦触发了单击事件,就会被该Grid捕获并进行处理。
另外,我们还通过路由事件的RoutedEventArgs参数获取到了触发该事件的控件。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值