title: TabControls containing different user controls using MVVM
body: <p>I am making a WPF application following MVVM. What I want in my application is that there is a View which contains some common buttons and text boxes and a <code>TabControl</code>. TabControl will basically host different <code>UserControls</code>. So for each <code>UserControl</code> I have a separate <code>View</code> and a <code>ViewModel</code> ready.</p>
  
  <p>So structure of my application looks like this.</p>
  
  <pre><code>MainWindow.Xaml
      EntryView.Xaml
          Button1
          Button2
          TabControl
              UserControl1 (View)
              UserControl2 (View)
              UserControl3 (View)
  </code></pre>
  
  <p>Son in my EntryView I have the tab control. Now I need to bind this.</p>
  
  <p>Here is what I have done.</p>
  
  <p><strong>EntryView.Xaml</strong></p>
  
  <pre><code>&lt;TabControl ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}"&gt;
      &lt;TabControl.ContentTemplate&gt;
          &lt;DataTemplate DataType="{x:Type vm:UserControl1ViewModel}"&gt;
              &lt;v:UserControl1View/&gt;
          &lt;/DataTemplate&gt;
          &lt;DataTemplate DataType="{x:Type vm:UserControl2ViewModel}"&gt;
              &lt;v:UserControl2View/&gt;
          &lt;/DataTemplate&gt;
      &lt;/TabControl.ContentTemplate&gt;
      &lt;TabControl.ItemTemplate&gt;
          &lt;DataTemplate&gt;
              &lt;TextBlock Text="Header"/&gt;
          &lt;/DataTemplate&gt;
      &lt;/TabControl.ItemTemplate&gt;
  &lt;/TabControl&gt;
  </code></pre>
  
  <p><strong>EntryViewModel.cs</strong></p>
  
  <pre><code>private ObservableCollection&lt;BaseViewModel&gt; _tabs;
  public ObservableCollection&lt;BaseViewModel&gt; Tabs
  {
      get
      {
          if (_tabs == null)
          {
              _tabs = new ObservableCollection&lt;BaseViewModel&gt;();
              _tabs.Add(new UserControl1ViewModel());
              _tabs.Add(new UserControl2ViewModel());
          }
          return _tabs;
      }
  }
  </code></pre>
  
  <p>But now when I run my application nothings happens. TabControl is empty. I put breakpoint inside Tabs in view model, but it didn't get hit. So question one is am I doing this right? If no then what should I do?</p>