tags:

views:

1285

answers:

1

How do you get 2 unrelated controls to raise the same custom event? All examples I have seen so far have an event defined inside 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.

+4  A: 

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));
}
Todd White
Thanks. Sorry, yes correct assumption about UIElement.GotFocusEvent.
MJS