使用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参数获取到了触发该事件的控件。
发布了359 篇原创文章 · 获赞 211 · 访问量 94万+

猜你喜欢

转载自blog.csdn.net/gjysk/article/details/38611015
今日推荐