作为我在这里阅读到的内容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>