我在WPF的文本框中注册了GotFocusEvent
的事件处理程序。
EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
现在,有没有办法从文本框中删除已注册的处理程序?
更新 我检查了以下链接
WPF Custom Routed Events - How to UnSubscribe?
然而,它并没有帮助我,因为上面提到的控件是自定义控件,因为在我的情况下它是默认的TextBox
控件。
我无法在我的案例中找到RemoveHandler
。有什么建议吗?
答案 0 :(得分:2)
如您问题的评论中所述,无法取消注册类处理程序。我给你的建议是:在你的处理程序的开头添加一个if语句,检查实际的方法体是否应该执行。这可能如下所示:
private void MyTextBoxClassHandler (object sender, RoutedEventArgs e)
{
if (CheckIfHandlerShouldExecute() == false)
return;
// The actual code that should be executed in the handler resides here.
}
这不会阻止调用处理程序,但如果不满足某个条件,则不会执行逻辑。
答案 1 :(得分:0)
无需注销类处理程序,但是您可以在静态类中管理事件,在该类中,您只需注册一次类处理程序,然后根据需要添加/删除实例处理程序。您可以公开普通的EventHandlers
,也可以使用反应式扩展来实现这一目标:
public static class GlobalEvents
{
static readonly ClassHandlerSubject s_TextBoxGotFocus = new ClassHandlerSubject(typeof(TextBox), UIElement.GotFocusEvent);
public static IObservable<RoutedEventArgs> TextBoxGotFocus => s_TextBoxGotFocus.Events;
class ClassHandlerSubject
{
readonly Lazy<Subject<RoutedEventArgs>> m_Subject;
public IObservable<RoutedEventArgs> Events => m_Subject.Value;
public ClassHandlerSubject(Type classType, RoutedEvent routedEvent) =>
m_Subject = new Lazy<Subject<RoutedEventArgs>>(() =>
{
EventManager.RegisterClassHandler(classType, routedEvent, new RoutedEventHandler(OnEventReceived));
return new Subject<RoutedEventArgs>();
});
private void OnEventReceived(object sender, RoutedEventArgs e) => m_Subject.Value.OnNext(e);
}
}
像这样使用它:
//subscribe
var subscription = GlobalEvents.TextBoxGotFocus.Subscribe(TextBox_GotFocus);
//... receive events
//remove my subscription
subscription.Dispose();