在WPF中,冒泡事件从引发事件的控件开始,沿着逻辑树或者可视树向上传递。与之相反,隧道事件则是从层次结构的顶点出发,由上至下传递直到传递到引发事件的控件。
下面的代码中我们给各层的控件都注册了PreviewKeyDown 事件,然后在最下面的TextBox中按键输入。
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
xmlns:loc="clr-namespace:WpfApplication11"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="WpfApplication11.MainWindow"
x:Name="Window" Title="Routed Events" Width="400"
PreviewKeyDown="winMain_PreviewKeyDown">
<StackPanel Name="spMain" Orientation="Vertical" PreviewKeyDown="spMain_PreviewKeyDown">
<Label Content="Some good movies:"/>
<StackPanel Orientation="Horizontal" Margin="10" PreviewKeyDown="spLawrence_PreviewKeyDown">
<Label Content="Lawrence of Arabia" FontWeight="Bold"/>
<Label Content="David Lean"/>
<Button Content="Like" Padding="8,0"/>
<TextBox Width="75" Margin="5,2" PreviewKeyDown="tbLawrence_PreviewKeyDown"/>
</StackPanel>
</StackPanel>
</Window>
显示结果:
原文地址:https://wpf.2000things.com/2012/06/21/585-tunneling-events-propagate-down-the-logical-tree/