事件冒泡在WPF应用程序 [英] Event Bubbling in WPF Application

查看:138
本文介绍了事件冒泡在WPF应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的WPF。在我的WPF应用程序,我的Windows包含一个用户定义的子控件​​和用户定义的子控件​​又包含另外一个用户定义的子控件​​。现在从最内侧的子控件,在点击一个按钮,我想火在所有三个控件(即第一个大孩子的控制,第二个孩子的控制,第三个主要的控制和窗口)。事件

I'm new to WPF. In my WPF app, I have Windows which contain a user defined child control and that user defined child control again contains another user defined child control. Now from the inner most child control, on a button click, I want to fire events on all three controls (i.e. First Grand Child Control, Second Child Control, Third Main Control, and Window).

我知道这可以通过委托和事件冒泡来实现。你能告诉我怎么样?

I know this can be achieved through delegates and Event Bubbling. Can you please tell me how?

推荐答案

最重要的一块PF code为: 添加事件处理程序的静态UIElement.MouseLeftButtonUpEvent:

Most important piece pf code for that: Add the event handlers on the static 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 

该事件处理:

The EventHandlers:

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
    }

这篇关于事件冒泡在WPF应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆