8.3.3 RoutedEventArgs的Source和OriginalSource
RoutedEventArgs有两个属性Source和OriginalSource,这两个属性都表示路由事件传递的起点(即事件消息的源头),只不过Source表示的是LogicalTree上的消息源头,而OriginalSource则表示VirtualTree上的源头。
<UserControl x:Class="FirstWpfApplication.Controls.UserControl1" xmlns="; xmlns:x="; xmlns:mc="; xmlns:d="; mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <Button x:Name="innerButton" Width="80" Height="80" Content="OK"/> </Grid></UserControl>
<Window x:Class="FirstWpfApplication.MainWindow" x:ClassModifier="public" xmlns="; xmlns:x="; xmlns:data="clr-namespace:System.Windows.Data;assembly=PresentationFramework" xmlns:local="clr-namespace:FirstWpfApplication" xmlns:controls="clr-namespace:FirstWpfApplication.Controls" Title="登录" Height="300" Width="300" > <Window.Resources> </Window.Resources> <Grid x:Name="grid"> <controls:UserControl1 x:Name="myUserControl" Margin="10" /> </Grid></Window>
/// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); this.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.Button_Click)); } private void Button_Click(object sender, RoutedEventArgs e) { string strOriginalSource = string.Format("VirtualTree start point:{0}, type is {1}", (e.OriginalSource as FrameworkElement).Name, e.OriginalSource.GetType().ToString()); string strSource = string.Format("LogicalTree start point:{0}, type is {1}", (e.Source as FrameworkElement).Name, e.Source.GetType().ToString()); MessageBox.Show(strOriginalSource + Environment.NewLine + strSource); } }
路由事件的宿主都是些拥有可视化实体的界面元素,而附加事件则不具备显示在用户界面上的能力。也就是说,附加事件的宿主没有界面渲染功能这双“飞翼”,但一样可以使用附加事件这个灵犀与其他对象进行沟通。
class Student { public static readonly RoutedEvent NameChangedEvent = EventManager.RegisterRoutedEvent ("NameChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(Student)); public int Id { get; set; } public string Name { get; set; } }
<Grid x:Name="grid"> <Button x:Name="button1" Content="OK" Width="80" Height="80" Click="Button_Click"/> </Grid>
public MainWindow() { InitializeComponent(); this.AddHandler(Student.NameChangedEvent, new RoutedEventHandler(this.StudentNameChangedHandler)); } private void Button_Click(object sender, RoutedEventArgs e) { Student stu = new Student() { Id = 10, Name = "Tim" }; RoutedEventArgs arg = new RoutedEventArgs(Student.NameChangedEvent, stu); this.button1.RaiseEvent(arg); } private void StudentNameChangedHandler(object sender, RoutedEventArgs e) { MessageBox.Show((e.OriginalSource as Student).Id.ToString()); }
联系客服