Dr1Ku
Dr1Ku

Reputation: 2910

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. 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!

Upvotes: 0

Views: 247

Answers (2)

Michael Kingsmill
Michael Kingsmill

Reputation: 1863

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.

Upvotes: 1

brunnerh
brunnerh

Reputation: 184506

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.

Upvotes: 3

Related Questions