看了半天的书才发现,路由事件其实就是程序对事件的监听方式,不是对某一控件的事件监听,而是对WPF控件树进行路由监听。事件发生时,事件会通过路由树到达某个事件点,发出是什么对象产生事件。
举例说明:在XAML文件中布局这样一段代码
<Grid> <StackPanel Name="Spname" Button.Click="but1_Click" > <Button Name="but1" > 点我1 </Button> <Button Name="but2" > 点我2 </Button> </StackPanel> </Grid>
在CS文件中放置这样一段代码
private void but1_Click(object sender, RoutedEventArgs e) { FrameworkElement fe = e.Source as FrameworkElement; if (Spname.Children.Contains(fe)) { this.Title = fe.Name + "<----"+(sender as FrameworkElement).Name; } }
e.Handled = true;//目的就是为了告诉程序路由事件已经处理,可以在其它路由中获得该值的情况。
}
运行一下,就知道什么是事件的路由了。
附加事件和路由事件相关:通过路由您可以附加一个事件后的事件。
XAML文件代码:
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type Button}"> <EventSetter Event="Click" Handler="blSETCOL"/> </Style> </Window.Resources> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Button Name="thisA" Click="Button_Click">thisA</Button> <Button Name="thisB" Click="thisB_Click" Grid.Column="1"> thisB </Button> </Grid> </Window>
CS文件代码:
private void blSETCOL(object sender, RoutedEventArgs e) { FrameworkElement ef = e.Source as FrameworkElement; MessageBox.Show("附加事件" + "<---" + ef.Name); } private void thisB_Click(object sender, RoutedEventArgs e) { this.Title = "thisB"; } private void Button_Click(object sender, RoutedEventArgs e) { this.Title = "thisA"; }
在显示效果的时候同样事件产生。
浙公网安备 33010602011771号