WPF中的路由事件是具有更强传播能力的事件,它们可以在元素树中向上冒泡和向下隧道传播,并且沿着传播路径被事件处理程序处理。
下面的例子演示了事件冒泡的过程。
<Window x:Class="Prj05_1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BubbledLabelClick" Height="359" Width="329">
<Grid Margin="3" MouseUp="SomethingClicked">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Label Margin="5" Grid.Row="0" HorizontalAlignment="Left" Background="AliceBlue" BorderBrush="Black" BorderThickness="1"
MouseUp="SomethingClicked">
<StackPanel MouseUp="SomethingClicked">
<TextBlock Margin="3" MouseUp="SomethingClicked">Image and text label</TextBlock>
<Image Source="lianjie.png" Stretch="None" MouseUp="SomethingClicked"/>
<TextBlock Margin="3" MouseUp="SomethingClicked">Courtesy of the StackPanel</TextBlock>
</StackPanel>
</Label>
<ListBox Grid.Row="1" Margin="5" Name="lstMessage"></ListBox>
<CheckBox Grid.Row="2" Margin="5" Name="chkHandle">Handle first event</CheckBox>
<Button Grid.Row="3" Margin="5" Padding="3" HorizontalAlignment="Right" Name="cmdCenter"
Click="cmdClear_Click">Clear List</Button>
</Grid>
</Window>
事件代码:
private void SomethingClicked(object sender, MouseButtonEventArgs e)
{
eventCounter++;
string message = "#" + eventCounter.ToString() + ":\r\n" +
" Sender:" + sender.ToString() + "\r\n" +
" Source: " + e.Source + "\r\n" +
" Original Source:" + e.OriginalSource;
lstMessage.Items.Add(message);
e.Handled = (bool)chkHandle.IsChecked;
}
private void cmdClear_Click(object sender, RoutedEventArgs e)
{
lstMessage.Items.Clear();
}
程序运行后的效果:
当点击Image时可以看到事件的响应过程是从最底层开始的。