WPF

WPF Tab Control – Close Button

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

<Grid>
        <Grid.Resources>
            <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}">
                        <Button.Template>
                            <ControlTemplate>
                                <Label FontWeight="Bold" Content="X" />
                            </ControlTemplate>
                        </Button.Template>
                    </Button>
                    <Label Content="{Binding ID}" />
                </DockPanel>
            </DataTemplate>

        </Grid.Resources>
        <TabControl x:Name="TabControl1"  
                    Margin="10"
                    ItemsSource="{Binding Employees}" 
                    ItemTemplate="{StaticResource CustomHeaderTemplate}">
</TabControl>

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
{
            get
            {
                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>;
            TabControl1.ClearValue(ItemsControl.ItemsSourceProperty);
            employees.RemoveAll(w => w.ID == (parameter as int?).GetValueOrDefault());
            TabControl1.ItemsSource = employees;
}

Here is the screenshot of TabControl with Close Button.

TabControl CloseButton