65.9K
CodeProject is changing. Read more.
Home

MVVM TabControl

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.40/5 (5 votes)

Mar 21, 2012

CPOL
viewsIcon

57826

This is a quick demonstration of how to use the standard WPF TabControl inside MVVM.

This is a quick demonstration of how to use the standard WPF TabControl inside MVVM.

First of all, I’ve just set up some very basic ViewModels:

This one is for each item (Tab) in the TabControl:

public class ItemViewModel : ViewModelBase
{
    private string name;

    public ItemViewModel(string tabName)
    {
        TabName = tabName;
    }

    public string TabName
    {
        get;
        private set;
    }

    public string Name
    {
        get
        {
            return name;
        }

        set
        {
            if (name != value)
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
    }
}

And this one is the main view model that contains the items:

public class MainViewModel : ViewModelBase
{
    private ObservableCollection<ItemViewModel> 
    items = new ObservableCollection<ItemViewModel>();

    public ObservableCollection<ItemViewModel> Items
    {
        get
        {
            return items;
        }
    }
}

Here, you can see an ObservableCollection of the items exposed. This is what will be bound to our TabControl via its ItemsSource property. This will look like the XAML below.

<TabControl
    ItemsSource="{Binding Items}">
    <TabControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding TabName}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
    <TabControl.ContentTemplate>
        <DataTemplate>
            <views:ItemView/>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

Here, the ItemTemplate is what’s used to display in the header of each tab and we’ve bound this to the TabName property from the ItemViewModel.

The ContentTemplate specifies the view that will be used. The ItemView instance will automatically inherit the ItemViewModel as its DataContext. Therefore, all binding inside that view will be based on an ItemViewModel.

We set the DataContext on the MainWindow to the MainViewModel and add some items like so:

var mainViewModel = new MainViewModel();
mainViewModel.Items.Add(new ItemViewModel("Tab 1"));
mainViewModel.Items.Add(new ItemViewModel("Tab 2"));

this.DataContext = mainViewModel;

Hopefully, that was fairly straightforward to follow and you can download the entire solution from here.