WPF Tab Control - Close Button

WPF  wpf 

A very common requirement in TabControl is to show a close button (X) near the end of header of each TabItem.

We can use ItemTemplate to customize the header section and show a close button (X) at the end of TabItem header.

Close Button Example

            <DataTemplate x:Key="CustomHeaderTemplate">
                <DockPanel LastChildFill="True">
                    <Button Content="X" DockPanel.Dock="Right" 
                            Command="{Binding DataContext.CloseCommand, RelativeSource={RelativeSource AncestorType={x:Type TabControl}}}"
                            CommandParameter="{Binding ID}">
                                <Label FontWeight="Bold" Content="X" />
                    <Label Content="{Binding ID}" />

        <TabControl x:Name="TabControl1"  
                    ItemsSource="{Binding Employees}" 
                    ItemTemplate="{StaticResource CustomHeaderTemplate}">

In the above code, I have customize the header template using ItemTemplate property of TabControl. I have taken a button with has content X as close. Using the DockPanel, I have moved close button as right align. Bind the button with CloseCommand. Below is the code for CloseCommand.

private RelayCommand closeCommand;

public RelayCommand CloseCommand
                if(this.closeCommand == null)
                    this.closeCommand = new RelayCommand(w => CloseCommandMethod(w), null);
                return this.closeCommand;

private void CloseCommandMethod(object parameter)
            List<Employee> employees = TabControl1.ItemsSource as List<Employee>;
            employees.RemoveAll(w => w.ID == (parameter as int?).GetValueOrDefault());
            TabControl1.ItemsSource = employees;

Here is the screenshot of TabControl with Close Button.

TabControl CloseButton

Join our newsletter and get an occasional email with a technology and DotNetPattern.com news update.