WPF自定义路由事件问题
-
07-07-2019 - |
题
如何获得两个不相关的控件以引发相同的自定义事件?到目前为止我看到的所有例子都在一个控件中定义了一个事件,我应该采用不同的方法吗?
EG。我想从OnFocus处理程序为按钮和文本框引发自定义冒泡事件。
解决方案
首先请允许我说你的问题并没有说明你不想使用现有的 UIElement.GotFocusEvent ,但我会假设您知道它并且有理由不使用它。
您始终可以在静态类上注册自定义事件,并将其提升到您想要的任何位置。 键盘课程及其所有事件(例如 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));
}
不隶属于 StackOverflow