Tuesday, November 21, 2017

TabControl with closeable TabItems in WPF/xaml

1. Introduction

The MoellonToolKit project  provide convenient dialog boxes and one useful component: a TabControl with closeable TabItems.
This project can be found on github here and packaged on nuget here.

2. Description, example

The MoellonToolKit project provides a TabControl with closable TabItem Headers. It is possible to use this TabControl with mixing closeable TabItems and standard (unclosable) TabItems.

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

The third and the fourth TabItems are closeable.

The image below shows the third closeable TabItem having the mouse over focus:

The cross of the TabItem is highlighted.

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




For more details, see the application sample named DevApp provided in the solution in the Dev folder in the github repository, the source code is available.



3. How ot use it in your application

-First step  is to download the nuget package in your solution and set it to your project.

-Declare the library containing the TabControl in the view. It can be a Window or a UserControl. The component is defined in the library: MoellonToolkit.CommonDlgs.Impl.


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

-Declare the TabControl in the View, Add standard TabItems and closeable TabItems as you want.

1
2
3
4
5
6
7
<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:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
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);
 }
}

No comments:

Post a Comment