RoutedEventArgs.Source vs Sender

前端 未结 4 1070
执念已碎
执念已碎 2020-12-05 11:44

What is the difference between sender and source in wpf event handling?

For example, say I had an ellipse in a canvas, and clicked on the ellipse:

4条回答
  •  执念已碎
    2020-12-05 12:19

    The difference between the two is not often seen, as usually the sender and Source are the same. Most code written like Windows Forms will basically ignore the difference and send them along as the same reference. However, given how WPF's event routing works they represent two different concepts.

    sender is the object at which the event handler was attached. This is the owner that raised the handler to begin routing the event. From MSDN:

    A difference between sender and Source is the result of the event being routed to different elements, during the traversal of the routed event through an element tree.

    MSDN: Event routing diagram

    Source is the object where the event originates. In the case of tunneling and bubbling, the Source will be one of their child elements. You can use the OriginalSource property to peel back any event tree encapsulation.

提交回复
热议问题