与依赖项属性类似,WPF也为路由事件提供了WPF事件系统这一组成。为一个类型添加一个路由事件的方式与为类型添加依赖项属性的方法类似,添加一个自定义路由事件的步骤:
一、声明路由事件变量并注册
定义只读的静态变量字段RouteEvent类来声明一个变量,然后使用EventManager的RegisterRoutedEvent()方法向事件系统注册路由事件,该方法的签名如下:
publicstaticRoutedEvent RegisterRoutedEvent(stringname, RoutingStrategy routingStrategy, Type handlerType, Type ownerType);
该方法带有四个参数:
第一个参数name表示该路由事件在WPF事件系统中的名称。第二个参数routingStrategy是RoutingStrategy类型的枚举值,标明了路由事件的路由策略,共三种策略:
EventManager的RegisterRouted } remove { RemoveHandler(MyClientEvent, value); } } /// <summary> /// 3、使用按钮的单击事件激发路由事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_Click(object sender, RoutedEventArgs e) { RoutedEventArgs arg = new RoutedEventArgs(); arg.RoutedEvent = MyClientEvent; RaiseEvent(arg); } }}
3、在主界面中引入新创建的用户控件,使用自定义的路由事件MyClick,并为MyClick事件编写调用的方法,XAML代码如下:
<Window x:Class="CustomWpfRouteEvent.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:u="clr-namespace:CustomWpfRouteEvent" Title="演示自定义路由事件" Height="350" Width="525" WindowStartupLocation="CenterScreen"> <Grid> <u:RouteEventControl MyClick="RouteEventControl_MyClick"></u:RouteEventControl> </Grid></Window>
4、www.easck.comRouteEventControl_MyClick方法的后台代码如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace CustomWpfRouteEvent{ /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void RouteEventControl_MyClick(object sender, RoutedEventArgs e) { MessageBox.Show("Hello:" + e.Source.ToString()); } }}5、运行程序,单击Button按钮,效果如下所示:

到此这篇关于WPF自定义路由事件的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。








