In this section, we are going to explore more about the effective tool of TabControl along with its functionalities, and methods.
TabControl allows you to have multiple pages on the same area and you can have different controls within each of the TabItem as well. We will be covering the following topics:
Setting Up TabControl #
Setting up TabControl is quite easy and simple. The steps are as follows:
Go to the TOOLBOX and select TabControl. Drag it to the WPF form.
To make it fit on the page, simply right-click the TabControl and select Fill Parent from the drop-down.
Changing the headers of TabItem #
You can change the headers of TabItems directly in the XAML Panel. For that, go to the designer tab and change the name in the field of Header as per your choice.
Adding new TabItems #
You can add new TabItems in the XAML panel by adding additional TabItem controls within the TabControl, like this:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Width="800" Height="400"> <Grid> <TabControl> <TabItem Header="Tab1"> <Grid Background="#FFE5E5E5"></Grid> </TabItem> <TabItem Header="Tab2"> <Grid Background="#FFE5E5E5"></Grid> </TabItem> <TabItem Header="Tab3"> <!-- Add a <TabITem> tag to add a new page --> <Grid Background="#FFE5E5E5"> <!-- Add a Grid to be able to insert multiple new controls --> </Grid> </TabItem> </TabControl> </Grid> </Window>
Switching Tabs during the design #
You can witness that, by default, the selected TabItem is the first one and you cannot change it by simply clicking. However, you can change the initial selected TabItem in two ways that are described below:
Changing the SelectedIndex in properties panel #
Go to the Common under the PROPERTIES of TabControl.
Find the option of SelectedIndex which is by default set at -1.
SelectedIndex property is zero-based meaning setting this value to 0 will select the first tab, setting to 1 the second one, etc.
You can add controls into each of the TabItems by dragging and dropping.
Note: You can keep on incrementing these numbers as per the total number of TabItems and your choice.
Changing the SelectedIndex of TabControl by DataContext #
To set the selected TabItem from the DataContext, the steps are as follows:
Go to the DATACONTEXT tab from the left sidebar.
Enter the initial index in any variable in JSON format. We have, for instance, set the value as 0 and stored it in ‘index’.
Under the PROPERTIES of TabControl, and select Common.
To the right of SelectedIndex, find the binding icon.
Click on it and select the property of ‘index’ (your created property in DataContext) from the dropdown.
It will automatically set that value as the selected TabItem. Also, it’s the initial value, you can always modify it when the application is running.
Properties, Methods and Events #
All of the properties, methods, and events can be found in Microsoft’s documentation at: