简体   繁体   English

从不同的来源收听同一事件

[英]Listening to the same Event from different sources

I was just wondering if C# / WPF had a ''syntax sugar-ed'' variant for listening to the same Event from different sources. 我只是想知道C#/ WPF是否有一个“语法糖化”变体来收听来自不同来源的同一事件。 I have a set up a single handler for a given event and I would like to have more controls listen to the same event, whilst using the same handler. 我为给定事件设置了一个处理程序,并且我想让更多的控件在使用相同处理程序的同时侦听同一事件。

Less talk, more code. 少说话,多代码。 Here's what I would like to achieve: 这是我想要实现的目标:

// Presuming pEnable is a parameter, a simple bool
if (pEnable) SomeControl.MouseDown += MyMouseDownEventHandler
        else SomeControl.MouseDown -= MyMouseEventHandler;

// How can I avoid repeating the snippet from above?
// E.g. Do the same for SomeOtherControl, ThisOtherControl and so on

The whole ternary operator can be dealt away with, I just wanted to post the whole code snippet I was thinking about. 整个三元运算符都可以解决,我只想发布我正在考虑的整个代码片段。 I can provide any other details if they seem sketchy. 如果它们看起来很粗略,我可以提供其他任何细节。

Thanks in advance! 提前致谢!

UPDATE: 更新:

It turns out that the proposed solution (see below) did not work out in my case since I was binding to a false event, in case of TreeView s this should be PreviewMouseDownEvent , and not the simple MouseDown events. 事实证明,由于我绑定到一个错误事件,因此在我的情况下,提出的解决方案(见下文) TreeView 。在TreeView的情况下,这应该是PreviewMouseDownEvent ,而不是简单的MouseDown事件。

Other than that, with the usage of RoutedEvent s (overview here ) one can also use AddHandler and RemoveHandler . 除此之外,通过使用RoutedEvent这里概述),还可以使用AddHandlerRemoveHandler More on that in this related question . 有关此问题的更多信息。 Thanks again for your input! 再次感谢您的输入!

Can't you just refactor this to a method which takes a control as parameter? 您能否将其重构为以控件为参数的方法?

void Listen(UIElement element)
{
    if (pEnable) element.MouseDown += MyMouseDownEventHandler
            else element.MouseDown -= MyMouseEventHandler;
}

Also those are routed events , you could handle the event on one common ancestor and then see what the source of the event is to act accordingly. 同样,这些事件路由事件 ,您可以在一个共同祖先上处理该事件,然后查看事件的根源是如何采取相应措施。

Since you are using WPF best thing to do would be to use MVVM style binding for these events and then bind the MouseDown event in XAML to the same method on the appropriate view model. 由于您使用的是WPF,因此最好的办法是对这些事件使用MVVM样式绑定,然后将XAML中的MouseDown事件绑定到相应视图模型上的相同方法。 This would allow you to remove this code all together from your code behind and leverage WPF's rich binding context. 这将使您可以从背后的代码中删除所有这些代码,并利用WPF的丰富绑定上下文。

You could then go a step further and template the controls that share the same event implementation so that you don't have to repeat the binding all throughout the XAML. 然后,您可以进一步走一步,对共享相同事件实现的控件进行模板化,从而不必在整个XAML中重复所有绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM