WPF 自定义路由事件

本文介绍如何在 C# 中创建自定义路由事件,并通过示例展示了如何在 WPF 应用程序中使用这些事件。文章详细解释了 AddHandler、RemoveHandler 和 RaiseHandler 的作用,以及如何与 UIElement 类一起使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C# codes:


using System.Windows;

namespace WpfApplication6
{
    public class Dog : UIElement //继承UIElement及其子类,因为AddHandler,RemoveHandler,RaiseHandler在UIElemnt中实现
    {
        public static readonly RoutedEvent RunRoutedEvent = 
            EventManager.RegisterRoutedEvent("Run", RoutingStrategy.Bubble, typeof(RunRoutedEventHandler), typeof(Dog));

        public event RunRoutedEventHandler Run //自定义事件,通过自定义时间为路由事件RunRoutedEvent加载、卸载方法
        {
            add { this.AddHandler(RunRoutedEvent, value); }
            remove { this.RemoveHandler(RunRoutedEvent, value); }
        }

        public void Invoker(RunRoutedEventArgs e) //自定义Invoke方法
        {
            this.RaiseEvent(e);
        }
    }

    public class RunRoutedEventArgs : RoutedEventArgs //自定义EventArgs,实现一个构造函数,参数包含RoutedEvent
    {
        public RunRoutedEventArgs(RoutedEvent routedEvent, object source)
            : base(routedEvent, source)
        { }

        public string Name { get; set; }
    }

    public delegate void RunRoutedEventHandler(object sender, RunRoutedEventArgs e); //自定义EventHandler
}


<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:proj="clr-namespace:WpfApplication6"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <proj:Dog x:Name="dog" Run="dog_Run" />
        <Button Content="Button" HorizontalAlignment="Left" Margin="143,101,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void dog_Run(object sender, RunRoutedEventArgs e)
        {
            MessageBox.Show("Sender: "+ sender.ToString() + 
                Environment.NewLine + "OriginalSource: "+ e.OriginalSource +
                Environment.NewLine + "Source: " + e.Source + 
                Environment.NewLine + "Dog Name: " + e.Name);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            this.dog.Invoker(new RunRoutedEventArgs(Dog.RunRoutedEvent, this) { Name = "Wangwang" });
        }
    }

个人感觉自定义路由事件类似于依赖属性,附加属性:

UIElement对应于DependencyObject,

Run事件包装器钟的AddHandler,RemoveHandler对应于依赖属性,附加属性的GetValue,SetValue方法

不同的是自定义路由事件需要一个RaiseEvent方法来Invoke事件中加载的方法。


AddHandler,RemoveHandler,RaiseHandler是RoutedEvent的三个最基础的方法,均定义在UIElement类中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值