WPF中自定义事件的事件冒泡?

时间:2011-01-15 04:48:08

标签: wpf wpf-controls

我在这里读到 http://msdn.microsoft.com/en-us/magazine/cc785480.aspx

WPF可以进行事件冒泡。但是,如果我想让自定义事件也从例如用户控件传递到父容器,该怎么办?就我所见,我无法看到这个解释。

1 个答案:

答案 0 :(得分:18)

此代码适用于我:

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));
    }
}

使用此代码,您可以注册以下事件:

<Grid>
    <StackPanel local:TestControl.Demo="TestControl_Demo" >
        <local:TestControl />
    </StackPanel>
</Grid>