Hi,
I am using a TabControl with MVVM pattern to create tabs by binding the ItemsSource property to a collection of viewmodels.
To do this, I am creating an ObservableCollection<ViewModelBase> on my main view model and binding the tab controls ItemsSource to this, similar to the following (pseudo)code (simplified to illustrate the concept):
Main view model, with observable collection of type ViewModelBase:
public class MainViewModel { private readonly ObservableCollection<ViewModelBase> m_tabViewModels = new ObservableCollection<ViewModelBase>(); public ObservableCollection<ViewModelBase> TabViewModels { get { return m_tabViewModels; } } }
XAML for the tab control, with tab control bound to tab view models collection:
<TabControl ItemsSource="{Binding TabViewModels}"></TabControl>
And then I have two viewmodels, TabViewModel1 and TabViewModel2, both subclasses of ViewModelBase:
public class TabViewModel1 : ViewModelBase {
private string m_description1; public string Description1 { get { return m_description1; } set { m_description1 = value; } } } public class TabViewModel2 : ViewModelBase {
private string m_description2; public string Description2 { get { return m_description2; } set { m_description2 = value; } } }
And finally some DataTemplates bound to these view models:
<DataTemplate DataType="{x:Type TabViewModel1}"><TextBox Text="{Binding Description1, Mode=TwoWay}"/></DataTemplate><DataTemplate DataType="{x:Type TabViewModel2}"><TextBox Text="{Binding Description2, Mode=TwoWay}"/></DataTemplate>
Now the problem is, if I add two viewmodels of the same type to the collection, I get two tabs with the same view template as expected. Problem is both tabs arebound to the same viewmodel - where I was expecting the viewmodel to be each separate instance I had added to the collection. Hence, when I edit the text box on one tab, when I change to the next tab with the same view model type (but different instance), its description property has changed too - it's the same view model instance.
Even if using the same view model type (and therefore same DataTemplate), I still want each tab bound to the separate view model instance even though they are of the same type. How do you properly achieve this using MVVM, and why isn't this example functioning as expected?
Thanks