IT干货网

wpf之WPF中自定义事件的事件冒泡

findumars 2026年05月17日 编程设计 88 0

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

WPF 可以进行事件冒泡。但是,如果我希望自定义事件也从用户控件冒泡到父容器怎么办?就我所见,我无法解释这一点。

请您参考如下方法:

这段代码对我有用:

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> 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!