Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65894582/subscribe-to-any-bubbled-up-wpf-child-control-routed-event-without-an-instance-o

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...