#906 – Programmatically Changing the Current Tab on a TabControl

You can change the currently selected tab on a TabControl in one of several ways:

  • Change the TabControl’s SelectedIndex property (0..n-1)
  • Change the TabControl’s SelectedItem property (if you have a reference to the TabItem for the tab that you want to switch to)
  • Use data binding and change the object that the SelectedItem is bound to

Below is an example of changing the SelectedIndex property when the user clicks on a Button.

        <TabControl Name="tabMeals">
            <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>
            <TabItem Header="Dinner">
                <StackPanel>
                    <RadioButton Content="Spam Sandwich"/>
                    <RadioButton Content="Spam Casserole"/>
                    <RadioButton Content="Spam Jello Surprise"/>
                </StackPanel>
            </TabItem>
        </TabControl>
        <Button Grid.Row="1" Content="Change Tabs" HorizontalAlignment="Center" Padding="10,5"
                Click="Button_Click"/>

 

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (tabMeals.SelectedIndex == (tabMeals.Items.Count - 1))
                tabMeals.SelectedIndex = 0;
            else
                tabMeals.SelectedIndex++;
        }

906-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: