<Window x:Class="WpfApplication1.Window26"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window26" Height="300" Width="300" xmlns:my="clr-namespace:WpfApplication1" WindowStyle="ToolWindow">
<Grid>
        <my:MyUserControl  Margin="10" x:Name="myUserControl1" />
    </Grid>
</Window>

---------------------------------------------------------------------------------------------------------

public partial class Window26 : Window
    {
        public Window26()
        {
            InitializeComponent();
            this.AddHandler(Button.ClickEvent, new RoutedEventHandler(ButtonClick));
        }        private void ButtonClick(object sender,RoutedEventArgs e)
        {
            string originSource = string.Format("VisualTree StartPoint:{0},type is {1}",(e.OriginalSource as FrameworkElement).Name,e.OriginalSource.GetType().Name);            string stringSource = string.Format("LogicTree startPoint:{0},Type is {1}",(e.Source as FrameworkElement).Name,e.Source.GetType().Name);
            MessageBox.Show(originSource+"\r\n"+stringSource);
        }
    }

 

 

路由事件_Source

 

 

 

     有没有想过在.NET中已经有了事件机制,为什么在WPF中不直接使用.NET事件要加入路由事件来取代事件呢?最直观的原因就是典型的WPF应用程序使用很多元素关联和组合起来,是否还记得在WPF自学入门(一)XAM基本知识中提到过两棵树,逻辑树LogicalTree 和可视化树 VisualTree,那么它们分别是什么?

举个例子:

路由事件_WPF_02

上面的代码就是逻辑树LogicalTree,一个Grid里面镶嵌了其他控件或布局组件,相当于一棵树中的叶子。而可视化树VisualTree是什么?它就是一个树中的树叶里面的结构,用放大镜看一下,其实叶子里面的结构也是一颗树结构

举个例子:

路由事件_WPF_03


1、WPF内置的路由事件


路由事件_Source_04

添加后置代码

路由事件_WPF_05

调试运行,鼠标右键点击按钮,会依次弹出下列三个对话框。

ButtonMouseDown事件被触发:

路由事件_WPF_06

 

GridMouseDown事件被触发:

路由事件_xml_07

 

WindowMouseDown事件被触发:

路由事件_xml_08

 









grid.AddHandler(Grid.MouseDownEvent, new RoutedEventHandler(Grid_MouseDown), true);


2、内置路由事件学习总结:

     气泡事件是WPF路由事件中最为常见,它表示事件从源元素扩散传播到可视树,直到它被处理或到达根元素。这样我们就可以针对源元素的上方层级对象处理事件。(例如MouseDown)






 


黄昏前黎明后