RoutedEventArgs的Source与OriginalSource

路由事件是沿着VisualTree传递。VisualTree与LogicalTree区别在于:LogicalTree的叶子是构成用户界面的控件,而VisualTree要连接控件中的细微结构也算上。

“路由事件在VisualTree上传递”本意上是说“路由事件的消息在VisualTree上传递”,而路由事件的消息包含在RoutedEventArgs实例中。
RoutedEventArgs有两个属性Source和OriginalSource,这两个属性都表示路由事件传递的起点,那么他们之间有什么区别那?
Source表示的是LogicalTree上消息的源头;
OriginalSource则表示VisualTree上的源头。

下面看一个例子:
首先定义一个用户控件:

<UserControl x:Class="WpfWindows8.MyUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfWindows8"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Border BorderBrush="Orange" BorderThickness="3" CornerRadius="5">
        <Button x:Name="innerButton" Width="80" Height="80" Content="OK" />
    </Border>
</UserControl>

这个控件包含一个名为innerBtton的Button控件,将此控件添加到主窗体上:

<Window x:Class="WpfWindows8.WinMain8_3_3"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfWindows8"
        mc:Ignorable="d"
        Title="Source v.s.OriginalSource" Height="180" Width="300" WindowStyle="ToolWindow">
    <Grid>
        <local:MyUserControl x:Name="myUserControl" Margin="10"/>
    </Grid>
</Window>

再在后台为主窗体添加对Button.Click路由事件的侦听:

 public WinMain8_3_3()
        {
            InitializeComponent();

            this.AddHandler(Button.ClickEvent, new RoutedEventHandler(this.Button_Click));
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string strOriginalSource = string.Format("VisualTree start point: {0}, type is {1}",
                (e.OriginalSource as FrameworkElement).Name, e.OriginalSource.GetType().Name);

            string strSource = string.Format("LogicalTree start point: {0}, type is {1}",
                (e.Source as FrameworkElement).Name, e.Source.GetType().Name);

            MessageBox.Show(strOriginalSource + "\r\n" + strSource);
        }

运行结果如下:
这里写图片描述这里写图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值