WPF中的事件(三)- 附加事件
2016-08-22 09:05
399 查看
附加事件的本质也是路由事件,路由事件的宿主是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。
界面效果如下:
相关文章推荐
- hdu 1047 1042 java 大整数
- 在ubuntu上使用swarm搭建docker集群
- Android setContentView()源码解析
- 一个苦逼SEO的哭诉:做SEO真的风光无限吗
- 空气质量
- 23 第三周作业
- Leetcode 382. Linked List Random Node
- 单例模式 来自百度百科
- mysql 5.7.14 安装全过程
- linux 正则表达式
- 用iReport设置pdf模版
- struct timeval结构体
- 了解android7了:多窗口支持
- 实现微信公众号自动登陆自己的Web App
- webpack入坑之旅(六)配合vue-router实现SPA
- emmet 缩写API
- C++中的运行时类型检查
- 两个Activity之间跳转时,生命周期的执行顺序
- servlet-web.xml配置
- libSVM笔记之(一)在matlab环境下安装配置libSVM