#905 – Executing Some Code when a User Changes Tabs on a TabControl

You can execute some code whenever a user changes tabs on a TabControl by handling the TabControl’s SelectionChanged event.  Below we have a TabControl and we define a handler for its SelectionChanged event.

    <Grid Margin="10">
            <RowDefinition Height="Auto"/>

        <TabControl SelectionChanged="TabControl_SelectionChanged">
            <TabItem Header="Breakfast">
                    <RadioButton Content="Eggs"/>
                    <RadioButton Content="Cereal"/>
                    <RadioButton Content="Spam"/>
            <TabItem Header="Lunch">
                    <RadioButton Content="Ham Sandwich"/>
                    <RadioButton Content="Soup"/>
                    <RadioButton Content="Wimpy Burger"/>
        <TextBlock Grid.Row="1" Name="txtMessage" Margin="0,5,0,0"/>

In our event handler, we simply change a text message, based on the tab that’s currently selected.

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    if ((sender as TabControl).SelectedIndex == 0)
        txtMessage.Text = "Start the day with a good breakfast";
        txtMessage.Text = "Have something healthy for lunch";