Skip to content

Closable TabItems in TabControl

yvlawy edited this page Dec 2, 2017 · 4 revisions

1. Description, Example

MoellonToolKit provides a TabControl with closable TabItem Headers. Its possible to use this TabControl with or without standart (unclosable) TabItems.

The example following implements a tabControl with 3 standart tabItems and 2 closeable TabItems:

The Information dialog box

The image below shows one closeable TabItem having the mouse focus:

The Information dialog box

Now, the image below shows the third tabItem removed because the user closed it:

The Information dialog box

For more details, see the application sample named DevApp provided in the solution in the Dev folder.

2. How to use it

First, declare the Library containing the TabControl in the view. On the example below, its a Window, but can be a UserControl. The component is defined in the Library: MoellonToolkit.CommonDlgs.Impl.

<Window x:Class="DevApp.Views.MainWindow"
      ...
      xmlns:tc="clr-namespace:MoellonToolkit.CommonDlgs.Impl;assembly=MoellonToolkit.CommonDlgs.Impl"
    ...

Declare the tabControl in the View, Add standart tabItem and closeable TabItems as you want.

    <tc:CloseableTabControl>
        <!-- standart tabItem, uncloseable -->
        <TabItem Header="Dialogs">
        ....

        <!-- Closeable tabItem-->
        <tc:CloseableTabItem Header="TabItem 3" />

The last action is to add some code into the behind class of the view:

    public MainWindow()
    {
        InitializeComponent();

        // for closing the Closeable tabItems
        this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));
    }

    /// <summary>
    /// Close the tabItem, by clic on the X.
    /// </summary>
    private void CloseTab(object source, RoutedEventArgs args)
    {
        TabItem tabItem = args.Source as TabItem;
        if (tabItem != null)
        {
            TabControl tabControl = tabItem.Parent as TabControl;
            if (tabControl != null)
                tabControl.Items.Remove(tabItem);
        }
    }