title: TabControl disposes of controls on inactive tabs
body: <p>I'm using the MVVM pattern for my app. The MainWindow comprises a <code>TabControl</code> with the <code>DataContext</code> mapped to the ViewModel:</p>
  
  <pre><code>&lt;Window.Resources&gt;
    &lt;ResourceDictionary&gt;
      &lt;DataTemplate x:Key="templateMainTabControl"&gt;
        &lt;ContentPresenter Content="{Binding Path=DisplayName}" /&gt;
      &lt;/DataTemplate&gt;
  
      &lt;local:ViewModel x:Key="VM" /&gt;
      &lt;local:WorkspaceSelector x:Key="WorkspaceSelector" /&gt;
      &lt;local:TabOneView x:Key="TabOneView" /&gt;
      &lt;local:TabTableView x:Key="TabTableView" /&gt;
  
      &lt;DataTemplate x:Key="TabOne"&gt;
        &lt;local:TabOneView /&gt;
      &lt;/DataTemplate&gt;
  
      &lt;DataTemplate x:Key="TabTable"&gt;
        &lt;local:TabTableView /&gt;
      &lt;/DataTemplate&gt;
  
    &lt;/ResourceDictionary&gt;
  &lt;/Window.Resources&gt;
  
  
  &lt;TabControl Grid.Row="0"
              DataContext="{StaticResource VM}"
              ItemsSource="{Binding Workspaces}"
              SelectedItem="{Binding SelectedWorkspace}"
              ItemTemplate="{StaticResource templateMainTabControl}"
              ContentTemplateSelector="{StaticResource WorkspaceSelector}" /&gt;
  </code></pre>
  
  <p>The <code>WorkspaceSelector</code> looks like:</p>
  
  <pre><code>public class WorkspaceSelector : DataTemplateSelector
  {
    public override DataTemplate SelectTemplate( object item, DependencyObject container )
    {
      Window win = Application.Current.MainWindow;
      Workspace w = ( Workspace ) item;
      string key = w.DisplayName.Replace( " ", "" );
      if ( key != "TabOne" )
      {
        key = "TabTable";
      }
      return win.FindResource( key ) as DataTemplate;
    }
  }
  </code></pre>
  
  <p>so that <code>TabOne</code> returns the <code>DataTemplate</code>. <code>TabOne</code> and the other two tabs return the <code>DataTemplate</code> <code>TabTable</code>.</p>
  
  <p>If I run the application and click on each of the tabs twice (1, 2, 3, 1, 2, 3) I don't get what I expect, which is</p>
  
  <p><br />TabOne's view is created
  <br />TabTwo's view is created
  <br />TabOne's View is created
  <br />TabTwo's view is created</p>
  
  <p>that is, if the <code>TemplateSelector</code> returns a different value, the existing tab's controls are thrown away and the new tab's control's are created, and if the <code>TemplateSelector</code> returns the same value, nothing happens.</p>
  
  <p>This is exactly what I don't want! I'd like the <code>TabControl</code> to keep all the controls on the tabs, and I would like to be able to do something about creating different controls in code for the case where I go from <code>TabTwo</code> to <code>TabThree</code>. I can live without the latter. But how do I tell the <code>TabControl</code> not to throw away each tab's controls when it's not selected? </p>