#905 – Executing Some Code when a User Changes Tabs on a TabControl
September 12, 2013 1 Comment
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"> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TabControl SelectionChanged="TabControl_SelectionChanged"> <TabItem Header="Breakfast"> <StackPanel> <RadioButton Content="Eggs"/> <RadioButton Content="Cereal"/> <RadioButton Content="Spam"/> </StackPanel> </TabItem> <TabItem Header="Lunch"> <StackPanel> <RadioButton Content="Ham Sandwich"/> <RadioButton Content="Soup"/> <RadioButton Content="Wimpy Burger"/> </StackPanel> </TabItem> </TabControl> <TextBlock Grid.Row="1" Name="txtMessage" Margin="0,5,0,0"/> </Grid>
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"; else txtMessage.Text = "Have something healthy for lunch"; }
Pingback: Dew Drop – September 13, 2013 (#1,623) | Morning Dew