我是WPF的新手。在我的WPF应用程序中,我有包含用户定义子控件的窗口,而该用户定义子控件又包含另一个用户定义子控件。现在,在最内部的子控件上,当单击按钮时,我想在所有三个控件(即第一大子控件、第二子控件、第三主控件和窗口)上触发事件。
我知道可以通过委托和事件冒泡来实现这一点。请问您如何做到?
我是WPF的新手。在我的WPF应用程序中,我有包含用户定义子控件的窗口,而该用户定义子控件又包含另一个用户定义子控件。现在,在最内部的子控件上,当单击按钮时,我想在所有三个控件(即第一大子控件、第二子控件、第三主控件和窗口)上触发事件。
我知道可以通过委托和事件冒泡来实现这一点。请问您如何做到?
最重要的代码片段是:
在静态UIElement.MouseLeftButtonUpEvent上添加事件处理程序:
middleInnerControl.AddHandler(UIElement.MouseLeftButtonUpEvent , new RoutedEventHandler(handleInner)); //adds the handler for a click event on the most out
mostOuterControl.AddHandler(UIElement.MouseLeftButtonUpEvent , new RoutedEventHandler(handleMostOuter)); //adds the handler for a click event on the most out
private void handleInner(object asd, RoutedEventArgs e)
{
InnerControl c = e.OriginalSource as InnerControl;
if (c != null)
{
//do whatever
}
e.Handled = false; // do not set handle to true --> bubbles further
}
private void handleMostOuter(object asd, RoutedEventArgs e)
{
InnerControl c = e.OriginalSource as InnerControl;
if (c != null)
{
//do whatever
}
e.Handled = true; // set handled = true, it wont bubble further
}