WPF中自定义事件的事件冒泡? [英] Event Bubbling for Custom Event in WPF?
本文介绍了WPF中自定义事件的事件冒泡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我在这里阅读时http://msdn.microsoft.com/en-us/magazine/cc785480.aspx
WPF 可以进行事件冒泡.但是,如果我希望自定义事件也从用户控件冒泡到父容器怎么办?就我所见,我无法解释这一点.
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.
推荐答案
这段代码对我有用:
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>
这篇关于WPF中自定义事件的事件冒泡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文