开发者

Event Bubbling for Custom Event in WPF?

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

开发者_StackOverflow中文版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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜