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.

Was it helpful?

Solution

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));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top