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!