我想在一次调用中挂钩所有可用的元素事件。像这样的一些事情:
elem.AddHandler(AnyRoutedEvent, (RoutedEventHandler)handler)
我怎样才能做到这一点?
我想在一次调用中挂钩所有可用的元素事件。像这样的一些事情:
elem.AddHandler(AnyRoutedEvent, (RoutedEventHandler)handler)
我怎样才能做到这一点?
试试这个来获取 Button 类型的所有事件......您可以替换不同的类型。
RoutedEvent[] events = EventManager.GetRoutedEventsForOwner(typeof(Button));
foreach (RoutedEvent e in events)
elem.AddHandler(e, handler);
您还可以替换以下内容以获取所有类型的所有路由事件,但这将是一个相当多的列表!
RoutedEvent[] events = EventManager.GetRoutedEvents();
您可以使用 EventManager 的 RegisterClassHandler 方法一次静态监听所有元素 :)
EventManager.RegisterClassHandler(typeof(your class), Button.ClickEvent, new RoutedEventHandler(OnButtonClick));
static void OnButtonClick(object sender, RoutedEventArgs e)
{
//Do awesome stuff with the button click
}
我的灵感来自: http: //geekswithblogs.net/tkokke/archive/2009/07/17/monitoring-routed-events-in-wpf.aspx
/// <summary>
/// This is used for debugging, when your looking for a specific event
/// </summary>
public static void RegisterAllEvents(Type type, FrameworkElement target)
{
var events = EventManager.GetRoutedEvents();
foreach (var routedEvent in events)
{
EventManager.RegisterClassHandler(type,
routedEvent, new RoutedEventHandler((sender, args) =>
{
if ( sender != target)
return;
System.Diagnostics.Debug.WriteLine(args.OriginalSource + "=>" + args.RoutedEvent);
}));
}
}