首页 > 代码库 > 获取路由事件的源Source和OriginalSource

获取路由事件的源Source和OriginalSource

路由事件的消息包括在RoutedEventArgs实例中,该实例有两个属性Source和OriginalSource,都是表示路由事件传递的起点。即事件消息的源头。仅仅只是Source表示的是LogicalTree上的消息源头,而OriginalSource表示的是VisualTree上的源头。

主要代码例如以下:
public MainWindow()
{
    InitializeComponent();
    this.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.ButtonClicked));
}


void ButtonClicked(object sender, RoutedEventArgs e)
{
    string SourceString = string.Format("LogicalTree start point: {0}, type is {1}",
        (e.Source as FrameworkElement).Name, e.Source.GetType().Name);
    string OriginalSourceString = string.Format("VisualTree start point: {0}, type is {1}",
        (e.OriginalSource as FrameworkElement).Name, e.OriginalSource.GetType().Name);


    MessageBox.Show(OriginalSourceString + "\r\n" + SourceString);
}


获取路由事件的源Source和OriginalSource