Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Bubbling for Custom Event in WPF?

As I read here http://msdn.microsoft.com/en-us/magazine/cc785480.aspx

WPF can do event bubbling. But what if I want a custom event to also bubble for example from a User Control to a parent container ? I can't see this explained as far as I can see.

like image 484
user310291 Avatar asked Jan 15 '11 04:01

user310291


1 Answers

This code works for me:

public class DemoEventArgs : RoutedEventArgs
{
    public DemoEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source)
    {}
}

public partial class TestControl : UserControl
{
    public static readonly RoutedEvent DemoEvent =
        EventManager.RegisterRoutedEvent(
            "Demo",
            RoutingStrategy.Bubble,
            typeof(RoutedEventHandler),
            typeof(TestControl));

    public event RoutedEventHandler Demo
    {
        add { AddHandler(DemoEvent, value); }
        remove { RemoveHandler(DemoEvent, value); }
    }

    public TestControl()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
         RaiseEvent(new DemoEventArgs(TestControl.DemoEvent, sender));
    }
}

Using this code you can register for the event like this:

<Grid>
    <StackPanel local:TestControl.Demo="TestControl_Demo" >
        <local:TestControl />
    </StackPanel>
</Grid>
like image 102
Emond Avatar answered Sep 23 '22 20:09

Emond