0

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 TreeViews this should be PreviewMouseDownEvent, and not the simple MouseDown events.

Other than that, with the usage of RoutedEvents (overview here) one can also use AddHandler and RemoveHandler. More on that in this related question. Thanks again for your input!

Community
  • 1
  • 1
Dr1Ku
  • 2,875
  • 3
  • 47
  • 56

2 Answers2

3

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.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I've tried it now and the events don't seem to "stick", must have something to do with the parameter passing, trying with _ref_. – Dr1Ku Feb 01 '12 at 12:52
  • 1
    @Dr1Ku: That won't change anything, if you want the events to be dynamically subscribed and unsubscribed you should handle this differently altogether, e.g. with a property for `pEnable` which has the method calls in its setter. That way whenever `pEnable` changes the event handlers are either removed or added. (Not sure if that is a very good idea architecture-wise though) – H.B. Feb 01 '12 at 14:17
  • Thanks again for the high-level solutions as well! Turns out I was subscribing to the wrong event :) – Dr1Ku Feb 01 '12 at 14:24
1

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.

Michael Kingsmill
  • 1,815
  • 3
  • 22
  • 31