WPF自定义路由事件问题

时间:2008-11-10 03:29:21

标签: wpf event-bubbling routed-events

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

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

1 个答案:

答案 0 :(得分:8)

首先请允许我说你的问题并没有明确表示你不想使用现有的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));
}