gpt4 book ai didi

c# - 如何删除 'Click' 的 'Button' 事件的所有事件处理程序?

转载 作者:可可西里 更新时间:2023-11-01 03:02:49 35 4
gpt4 key购买 nike

我有一个按钮控件,我需要删除所有附加到其 Click event 的事件处理程序.

这怎么可能?

Button button = GetButton();
button.Click.RemoveAllEventHandlers();

最佳答案

Note: Since the question on which I posted my original answer was closed as a duplicate of this question, I'm cross-posting an improved version of my answer here. This answer only applies to WPF. It will not work on Windows Forms or any other UI framework.

下面是一个有用的实用方法,用于删除订阅给定元素上的路由事件的所有事件处理程序。如果愿意,您可以简单地将其转换为扩展方法。

/// <summary>
/// Removes all event handlers subscribed to the specified routed event from the specified element.
/// </summary>
/// <param name="element">The UI element on which the routed event is defined.</param>
/// <param name="routedEvent">The routed event for which to remove the event handlers.</param>
public static void RemoveRoutedEventHandlers(UIElement element, RoutedEvent routedEvent)
{
// Get the EventHandlersStore instance which holds event handlers for the specified element.
// The EventHandlersStore class is declared as internal.
var eventHandlersStoreProperty = typeof(UIElement).GetProperty(
"EventHandlersStore", BindingFlags.Instance | BindingFlags.NonPublic);
object eventHandlersStore = eventHandlersStoreProperty.GetValue(element, null);

// If no event handlers are subscribed, eventHandlersStore will be null.
// Credit: https://stackoverflow.com/a/16392387/1149773
if (eventHandlersStore == null)
return;

// Invoke the GetRoutedEventHandlers method on the EventHandlersStore instance
// for getting an array of the subscribed event handlers.
var getRoutedEventHandlers = eventHandlersStore.GetType().GetMethod(
"GetRoutedEventHandlers", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
var routedEventHandlers = (RoutedEventHandlerInfo[])getRoutedEventHandlers.Invoke(
eventHandlersStore, new object[] { routedEvent });

// Iteratively remove all routed event handlers from the element.
foreach (var routedEventHandler in routedEventHandlers)
element.RemoveHandler(routedEvent, routedEventHandler.Handler);
}

然后您可以轻松地为按钮的 Click 事件调用此实用程序方法:

RemoveRoutedEventHandlers(button, Button.ClickEvent);

编辑:我复制了bug fix implemented by corona ,这会在没有订阅任何事件处理程序时阻止该方法抛出 NullReferenceException。信用(和赞成票)应该归功于他们的回答。

关于c# - 如何删除 'Click' 的 'Button' 事件的所有事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6828054/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com