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: the ellipse would be both the sender and the source.
However if the ellipse doesn't handle the event but the main window does, the event will pass through the canvas... so the canvas would be the sender of the event to the main window but the source would be the ellipse.
Do I have that right?
A routed event is an event registered with the WPF event system, backed by an instance of the RoutedEvent class, and processed by the WPF event system. The RoutedEvent instance, obtained from registration, is typically stored as a public static readonly member of the class that registered it.
Remarks. Different RoutedEventArgs can be used with a single RoutedEvent. This class is responsible for packaging the event data for a RoutedEvent, providing extra event state information, and is used by the event system for invoking the handler associated with the routed event.
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.
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.
Bubbles!
The sender is the object that the event is being raised from, whereas source was the original element that is causing the event to be raised.
Like in this case:
<TabControl Name="tc1" SelectionChanged="tc1_SelectionChanged">
<TabItem Header="1">
<TabControl Name="tc2">
<TabItem Header="1" />
<TabItem Header="2" />
</TabControl>
</TabItem>
<TabItem Header="2" />
</TabControl>
private void tc1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
In this case, if you change the SelectedItem
on the Sub-TabControl
, sender
will equal tc1
, Source
will equal tc2
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With