Search code examples
c#wpfxamltabcontroltabitem

Dynamic TabControl in WPF MVVM


I started using WPF (in C#) some weeks ago and now i need help for some advanced use of tabcontrol.

Fisrt of all, I'm using a MVVM (Model View ViewModel) pattern for designing my application, and I have a constraint that is to try to not add code in code behind file (that inititalise xaml files).

Now my issue is to create dynamically new tabItems in my MainWindow View (Window) that shows an instance of my Detail View (Page) when I click on a button ("New Tab" button for example).

I have found a lot off stuff about dynamic creation off tabitem on the web but often with modifications in code behind files. I though using binding but I don't know how can I use binding to this kind of stuff.


Solution

  • MVVM will help you out.

    Create a ViewModel for your MainWindow View. There you can have a collection of DetailViewModels. Just use an ObservableCollection of DetailViewModels here.

    In your View, bind the ItemsSource of the TabControl to that Collection.

    Your AddTab Button can have a Command Binding. That Command can be a ICommand derived class, that is published in the MainWindowViewModel. Pressing the button then ends up in the MainWindow ViewModel, adding another DetailViewModel and updating the View that way.

    Have a look to this excellent video tuturial on MVVM here: Jason Dollinger on MVVM

    He explains how that can be made, with examples for Main and Detail ViewModel and commands.

    The sourcecode that he develops in his video is available here: Sourcecode on Lab49

    Perhaps it even easier for you to create a ViewModel that is just used by the TabControl. Set the DataContext of the TabControl to that TabControlViewModel then. Publish that TabControlViewModel in your MainWindowViewModel as a public property, to accomplish that.

    Your code-behind will be empty, except some InitializeComponent perhaps.