#499 – Interacting with the Control That Initiated an Event

In WPF, you do not have to provide a name for every control in your user interface.  Since so much is accomplished through data binding, you often don’t need to interact with a control at all from your code.

But one scenario where you might want to interact with a control is from an event handler for an event that the control initiated.  Every event handler will have a sender argument that represents the control that fired the event.  You can cast this argument to the appropriate type to get at the original control.

<Button Content="Click Me" HorizontalAlignment="Center" Padding="10,5" Margin="10"
        Click="Button_Click"/>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            b.Width = b.ActualWidth + 1;
        }
Advertisements