Event Bubbling in WPF Application

时光怂恿深爱的人放手 提交于 2019-12-22 07:58:28

问题


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?


回答1:


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
    }



回答2:


Have a look at this http://msdn.microsoft.com/en-us/library/ms742806.aspx




回答3:


This page explains all about routed events, including how to implement and consume them.



来源:https://stackoverflow.com/questions/6452611/event-bubbling-in-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!