Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

MVVM TabControl

0.00/5 (No votes)
21 Mar 2012 1  
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here