WPF应用程序中的事件冒泡

4

我是WPF的新手。在我的WPF应用程序中,我有包含用户定义子控件的窗口,而该用户定义子控件又包含另一个用户定义子控件。现在,在最内部的子控件上,当单击按钮时,我想在所有三个控件(即第一大子控件、第二子控件、第三主控件和窗口)上触发事件。

我知道可以通过委托和事件冒泡来实现这一点。请问您如何做到?

3个回答

6

最重要的代码片段是:

在静态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
    }

为什么不使用ClickEvent - Snowbear
当然可以。我没有仔细阅读,没看到它是一个被点击的按钮。 - fixagon


1

这个页面详细解释了路由事件的所有内容,包括如何实现和使用它们。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接