【问题标题】:WPF Custom Routed event questionWPF 自定义路由事件问题
【发布时间】:2010-09-21 13:51:53
【问题描述】:

如何让两个不相关的控件引发相同的自定义事件?到目前为止,我看到的所有示例都在单个控件中定义了一个事件,我应该采取不同的方法吗?

例如。我想从按钮和文本框的 OnFocus 处理程序中引发自定义冒泡事件。

【问题讨论】:

    标签: wpf event-bubbling routed-events


    【解决方案1】:

    首先让我说你的问题并没有表明你不想使用现有的UIElement.GotFocusEvent,但我假设你知道它并且有你不使用它的理由。

    您始终可以在静态类上注册自定义事件,并在您想要的任何地方引发它。 Keyboard class 处理它的所有事件(例如Keyboard.KeyDownEvent)。

    public static class RoutedEventUtility
    {
        public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent("MyCustomEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RoutedEventUtility));
    }
    

    您像引发任何其他 RoutedEvent 一样引发事件。

    RoutedEventArgs args = new RoutedEventArgs(RoutedEventUtility.MyCustomEvent);
    RaiseEvent(args);
    

    如果您希望其他班级将事件作为公共字段拥有,那么您需要添加一个所有者。

    public class MyCustomControl : Control
    {
        public static readonly RoutedEvent MyCustomEvent = RoutedEventUtility.MyCustomEvent.AddOwner(typeof(MyCustomControl));
    }
    

    【讨论】:

    • 谢谢。抱歉,是的关于 UIElement.GotFocusEvent 的正确假设。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多