Search code examples
wpfmvvmview

MVVM - WPF Desktop


Just started learning MVVM. I have a tabcontrol where I am adding multiple instances of same views/pages

    Dim tb As New UXTabItem

    tb.Header = "Childrens"

    tb.Name = "tab" & itrt
    itrt = itrt + 1

    tb.Source = New Uri("/Views/childrens.xaml", UriKind.Relative)
UXTabControl1.Items.Add(tb)

Since each of the same view will handle different data but since the uri is same so all the tabs get populated with same view and changes reflect on each tabs. Which should not be the case. Should I be using a separate viewmodel for each of those? Any example would be much helpful.


Solution

  • One of the primary goals/advantages of MVVM is that you don't create WPF UI objects in code.

    You should be populating a collection of view model objects and binding the ItemsSource of the TabControl that you define in XAML to it. You should have a DataTemplate defined for the data type of those objects and put their XAML in there, instead of loading it at runtime.

    The TabControl is a little tricky, because it uses two templates: the ItemTemplate is used to define the look of the tab, and the ContentTemplate is used to define the look of the tab items' content. It's pretty common to see this:

    <TabControl ItemsSource="{Binding MyItems}">
       <TabControl.ItemTemplate>
          <DataTemplate>
             <TextBlock Text="{Binding Text}"/>
          </DataTemplate>
       </TabControl.ItemTemplate>
       <TabControl.ContentTemplate>
          <DataTemplate>
             <ContentPresenter Content="{Binding}"/>
          </DataTemplate>
       </TabControl.ContentTemplate>
    </TabControl>
    

    which populates the tab with a Text property on the view model, and the tab item's content with whatever template in the resource dictionary matches the view model's type.