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參數獲取到了觸發該事件的控件。