Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Custom Routed event question

How do you get two unrelated controls to raise the same custom event? All examples I have seen so far have an event defined within a single control, should I be taking a different approach?

Eg. I'd like to raise a custom bubbling event from an OnFocus handler for a button and a textbox.

like image 491
MJS Avatar asked Nov 10 '08 03:11

MJS


1 Answers

First off let me say your question doesn't make it clear that you don't want to use the existing UIElement.GotFocusEvent, but I'll assume you know about it and have your reasons for not using it.

You can always register a custom event on a static class, and raise it wherever you want. The Keyboard class does with all of its events (e.g. Keyboard.KeyDownEvent).

public static class RoutedEventUtility
{
    public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent("MyCustomEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RoutedEventUtility));
}

You raise the event just like you would any other RoutedEvent.

RoutedEventArgs args = new RoutedEventArgs(RoutedEventUtility.MyCustomEvent);
RaiseEvent(args);

If you want another class to own the event as a public field then you will need to add an owner.

public class MyCustomControl : Control
{
    public static readonly RoutedEvent MyCustomEvent = RoutedEventUtility.MyCustomEvent.AddOwner(typeof(MyCustomControl));
}
like image 84
Todd White Avatar answered Nov 03 '22 00:11

Todd White