Event Bubbling in WPF Application

Abhi picture Abhi · Jun 23, 2011 · Viewed 10k times · Source

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?

Answer

fixagon picture fixagon · Jun 23, 2011

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
    }