wpfrouted-events

Subscribe to any bubbled-up WPF child control routed event without an instance of a child control


I've got a WPF Custom control containing a canvas showing multiple child objects and (possibly) ItemsControls. I have no idea how many child objects there will be or how nested they will be.

But I need this control to catch any "bubbled-up" Thumb.DragCompleted events from any child Thumb. The problem is, it does not have any particular instance of a Thumb control to subscribe to. It just needs to catch the event regardless and take a certain action if the thumb meets certain criteria.

Is it possible to subscribe to all such child events in code-behind? The closest I can see appears to be EventManager.RegisterClassHandler but I don't want a DragCompleted for every thumb in the application, just the ones for my child objects. I must be missing some obvious function, yes?

The examples I find seem to expect that you actually have a Thumb control object instance.


Solution

  • You can subscribe to a bubbling-type routed event in XAML like so:

    <Grid Name="ParentGrid" Thumb.DragCompleted="DragCompletedEventHandler">
        <!--Some children possibly containing a Thumb-->
    </Grid>
    

    In the above example, any Thumb inside ParentGrid that raises its DragCompleted event will eventually call DragCompletedEventHandler (provided another handler deeper in the tree does not get called first and set RoutedEventArgs.Handled to True, which would stop the propagation).

    You can accomplish the same thing in code like this:

    ParentGrid.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler(DragCompletedEventHandler));
    

    Where ParentGrid is the parent control at the level at which you want to listen.