使用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 · 訪問量 95萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章