Search code examples
wpfrouted-events

Routed Events in WPF - using an Action delegate


I'm developing a user control, and wish to use a routed event. I notice that there are two delegates provided - RoutedEventHandler, and RoutedPropertyChangedEventHandler. The first that doesn't pass along any information, and the second that takes the old and new values of a property change. However, I need to pass just a single piece of information, so I want the equivalent of an Action delegate. Is there anything provided? Can I use an Action delegate?


Solution

  • Create a subclass of RoutedEventArgs to hold your additional data, and use EventHandler<T> with your args class. This will be convertible to RoutedEventHandler and the additional data will be available in your handlers.

    You could create a generic RoutedEventArgs class that holds a single parameter of any type, but creating a new class usually makes the code easier to read and easier to modify to include more parameters in the future.

    public class FooEventArgs
        : RoutedEventArgs
    {
        // Declare additional data to pass here
        public string Data { get; set; }
    }
    
    public class FooControl
        : UserControl
    {
        public static readonly RoutedEvent FooEvent =
            EventManager.RegisterRoutedEvent("Foo", RoutingStrategy.Bubble, 
                typeof(EventHandler<FooEventArgs>), typeof(FooControl));
    
        public event EventHandler<FooEventArgs> Foo
        {
            add { AddHandler(FooEvent, value); }
            remove { RemoveHandler(FooEvent, value); }
        }
    
        protected void OnFoo()
        {
            base.RaiseEvent(new FooEventArgs()
            {
                RoutedEvent = FooEvent,
                // Supply the data here
                Data = "data",
            });
        }
    }