WPF中的事件(三)- 附加事件

来源:互联网 发布:java 随机数生成 编辑:程序博客网 时间:2024/05/01 22:53
附加事件的本质也是路由事件,路由事件的宿主是Button、Grid等这些我们可以在界面上看得见的控件对象,而附加事件的宿主是Binding类、Mouse类、KeyBoard类这种无法在界面显示的类对象。附加事件的提出就是为了让这种我们无法看见的类也可以通过路由事件同其他类对象进行交流。下面我们先定义一个包含附加事件的类:
public 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; }    }
可以看到,附加事件的声明和路由事件完全一样,和路由事件不同的是它并非派生自UIElement,因此没有AddHandler和RemoveHandler两个方法,且没有RaiseEvent这个方法可以激发事件,只能附加到UIElment对象上面进行激发。 搭建以下的界面:
<Window x:Class="_8_14.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">    <Grid Name="gridMain">        <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="219,266,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />    </Grid></Window>
我们要实现的效果时,在修改Student对象的name属性时,激发Student.NameChangedEvent事件,在界面中设置该附件事件的处理器,弹出被修改姓名的Student对象的id。
public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            this.gridMain.AddHandler(Student.NameChangedEvent,                new RoutedEventHandler(this.StudentNameChangedHandler));        }        private void button1_Click(object sender, RoutedEventArgs e)        {            Student stu = new Student            {                id = 101,                name = "Tim"            };            stu.name = "Tom";            RoutedEventArgs args = new RoutedEventArgs(Student.NameChangedEvent, stu);            this.button1.RaiseEvent(args);        }  private void StudentNameChangedHandler(object sender, RoutedEventArgs e)        {            MessageBox.Show((e.OriginalSource as Student).id.ToString());        }    }

button1_Click为界面上按钮的处理事件,在这个事件中我们定义了一个Student的对象,然后修改Student对象的name属性,由于Student对象没有RaiseEvent方法,这里需要借助button1的RaiseEvent方法激发该路由事件。
在MainWindow的构造函数中,为gridMain增加了该路由事件Student.NameChangedEvent的处理器,在处理器的委托函数中,弹出该Student对象对应的id。
界面效果如下:
这里写图片描述
这里写图片描述

0 0
原创粉丝点击