我是 WPF 新手。在我的 WPF 应用程序中,我的 Windows 包含一个用户定义的子控件,并且该用户定义的子控件再次包含另一个用户定义的子控件。现在,从最里面的子控件单击按钮,我想在所有三个控件(即第一个大子控件、第二个子控件、第三个主控件和窗口)上触发事件。
我知道这可以通过委托(delegate)和事件冒泡来实现。你能告诉我怎么做吗?
最佳答案
最重要的 pf 代码: 在静态 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
}
关于c# - WPF 应用程序中的事件冒泡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6452611/