从不同来源监听同一事件
我只是想知道 C# / WPF 是否有一个“语法糖化”变体来监听来自不同来源的相同事件。我为给定事件设置了一个处理程序,我希望有更多控件侦听相同事件,同时使用相同 > 处理程序。
少说话,多写代码。这就是我想要实现的目标:
// 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
整个三元运算符可以被处理,我只是想发布我正在考虑的整个代码片段。如果其他细节看起来很粗略,我可以提供。
提前致谢!
更新:
事实证明,所提出的解决方案(见下文)在我的情况下不起作用,因为我绑定到错误事件,在 TreeView
的情况下,这应该是 PreviewMouseDownEvent
,而不是简单的 MouseDown
事件。
除此之外,使用 RoatedEvent
(概述 此处)还可以使用AddHandler
和RemoveHandler
。有关更多信息,请参阅此相关问题。再次感谢您的意见!
I was just wondering if C# / WPF had a ''syntax sugar-ed'' variant for listening to the same Event from different sources. 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.
Other than that, with the usage of RoutedEvent
s (overview here) one can also use AddHandler
and RemoveHandler
. More on that in this related question. Thanks again for your input!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
难道您不能将其重构为以控件作为参数的方法吗?
这些也是路由事件,您可以在一个共同的祖先上处理该事件然后查看事件的来源是什么来采取相应的行动。
Can't you just refactor this to a method which takes a control as parameter?
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.
由于您使用的是 WPF,最好的做法是对这些事件使用 MVVM 样式绑定,然后将 XAML 中的 MouseDown 事件绑定到相应视图模型上的相同方法。这将允许您从代码隐藏中一起删除这些代码,并利用 WPF 丰富的绑定上下文。
然后,您可以更进一步,对共享相同事件实现的控件进行模板化,这样您就不必在整个 XAML 中重复绑定。
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. This would allow you to remove this code all together from your code behind and leverage WPF's rich binding context.
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.