How to Add Close and Create Buttons to the Tab Headers using MVVM approach
Since R2 2019 the RadTabItem supports built-in close and pin buttons. Read more about this in the Pin and Close article.
The goal of this tutorial is to create a RadTabControl with closable tab items using an MVVM approach.
It demonstrates how to close and create new items using close and add buttons placed in the tab header as shown on the snapshot bellow:
For the purpose of this example, you will need to create an empty WPF application project and open it in Visual Studio.
The first step is to add references to the assemblies Telerik.Windows.Controls and Telerik.Windows.Controls.Navigation.
Then we need to define our ViewModels. We can start by creating a class to describe the RadTabItems - TabViewModel exposing a Header property. As we're taking an MVVM approach to implement the Add and Close buttons functionality, we'll also have to set up Add and Close commands in the TabViewModel.
Example 1: Create ViewModels
- After that we can go ahead and create a MainViewModel to define the collection of TabViewModel items which we will use to populate the RadTabControl.ItemsSource. Please note that as the add/close logic will change the RadTabControl.ItemsSource collection, it's best to implement the commands execution methods in this ViewModel as well:
Example 2: Creating TabViewModel
Now that our ViewModels are all in place, we can proceed with the definition of our view. In order to take full advantage of the implemented commands we have to bind the Add/Close Buttons Command properties to the appropriate DelegateCommands definitions.
Here is how the Resources section of our view looks like:
Example 3: Binding buttons Command property
- And here is the RadTabControl definition:
Example 4: Defining RadTabControl
Please note that in the above sample we have defined custom styles for the Button controls which you can remove or modify accordignly to your requirements.