WPF TabControl provides two templates property for changing the UI for Header and Content area.
- ItemTemplate – Get/Set DataTemplate for TabItem Header.
- ContentTemplate – Get/Set DateTemplate for TabItem Content.
ItemTemplate
ItemTemplate is used for changing the DataTemplate of Header section of TabItem. By default, Header DataTemplate call the ToString method of binded object to get the content of it.
You can define your custom DataTemplate and set using the ItemTemplate property of TabControl. You can set ItemTemplate using either Inline or set the ItemTemplate property using StaticResource or DynamicResource.
<TabControl x:Name="TabControl1" Margin="10">
<TabControl.ItemTemplate>
<DataTemplate>
<Label Background="Yellow" Foreground="Red" Content="{Binding ID}" />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
ContentTemplate
ContentTemplate is used for changing the DataTemplate of Content section of TabItem. By default, Content DataTemplate call the ToString method of binded object to get the content of it.
<TabControl x:Name="TabControl1" Margin="10">
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding FirstName}" />
<TextBlock Text="{Binding LastName}" />
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
Full example of TabControl with ItemTemplate and ContentTemplate
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Tab Control ItemTemplate ContentTemplate Example" Height="350" Width="525">
<Grid>
<Grid.Resources>
<DataTemplate x:Key="CustomHeaderTemplate">
<Label Background="Yellow" Content="{Binding ID}" />
</DataTemplate>
<DataTemplate x:Key="CustomItemTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding FirstName}" />
<TextBlock Grid.Column="1" Text="{Binding LastName}" />
</Grid>
</DataTemplate>
</Grid.Resources>
<TabControl x:Name="TabControl1"
Margin="10"
ItemTemplate="{StaticResource CustomHeaderTemplate}"
ContentTemplate="{StaticResource CustomItemTemplate}">
</TabControl>
</Grid>
</Window>
using System.Collections.Generic;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Employee> employees = new List<Employee>();
employees.Add(new Employee { ID = 1, FirstName = "Kapil", LastName = "Malhotra" });
employees.Add(new Employee { ID = 2, FirstName = "Joe", LastName = "Yarbrough" });
TabControl1.ItemsSource = employees;
}
}
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
}