#603 – Sender, Source and OriginalSource Example

Event handlers for routed events in WPF will have access to three different user interface elements within the handler:

  • sender – the element that raised the event
  • e.Source – element where the event originated
  • e.OriginalSource – original low-level element where the event originated (e.g. sub-element in a control)

Suppose that we have the following logical tree:

    <StackPanel Orientation="Vertical" UIElement.MouseMove="StackPanel_MouseMove">
        <Button Content="Move Mouse Over Me" MouseMove="Button_MouseMove"/>
    </StackPanel>

When we move the mouse over the text on the Button, the MouseMove event fires, first on the Button itself and then on the StackPanel (because MouseMove is a bubbling event).  Here are the values of the three fields when you handled each of these events:

  • MouseMove fires on the Button
    • senderButton
    • SourceButton
    • OriginalSource = TextBlock (the TextBlock that is a child control of the Button)
  • MouseMove fires on the StackPanel
    • senderStackPanel
    • Source = Button
    • OriginalSource = TextBlock
Advertisements