title: WPF TabControl - Cannot programmatically select tabs
body: <p>I have a user interface with a TabControl that initially displays a start page.  Other items can be added to it by double-clicking on content in, for example, a DataGrid.  New tabs should be selected when they are created. If the document corresponding to the item in the grid is already open, then the existing tab for that document should be opened rather than creating a new one.</p>
  
  <p>I know that I should be able to programmatically select a tab by setting the TabControl's SelectedItem or SelectedIndex properties.  However, the desired tab never actually activates.  If I set one and then inspect the TabControl's state in the debugger, then both fields seem to update properly.  However, after I continue execution, I see that the selected tab remains unchanged in the UI, and if I pause and inspect the TabControl's state again I see that the SelectedItem and SelectedIndex have returned to their previous values.   Selecting a tab by clicking on it in the UI, on the other hand, works just fine.</p>
  
  <p>Here's the declaration for the TabControl:</p>
  
  
  
  <pre class="lang-xml prettyprint-override"><code>&lt;TabControl x:Name="Tabs" &gt;
      &lt;TabItem x:Name="StartPageTab" Header="Start Page" DataContext="{Binding Path=StartPageViewModel}"&gt;
          ...
      &lt;/TabItem&gt;
  &lt;/TabControl&gt;
  </code></pre>
  
  <p>And the code for adding and selecting tabs:</p>
  
  <pre><code>private void _SelectTab(MyViewModel model)
  {
      TabItem tab;
      if (_TryFindTab(model, out tab)) Tabs.SelectedItem = tab;
  }
  
  private bool _TryFindTab(MyViewModel target, out TabItem tab)
  {
      foreach (TabItem item in Tabs.Items)
      {
          MyViewModel model = item.DataContext as MyViewModel;
          if (model != null &amp;&amp; model.Equals(target))
          {
              tab = item;
              return true;
          }
      }
      tab = null;
      return false;
  }
  
  private void _AddTab(MyViewModel model)
  {
      TabItem tab = new TabItem { DataContext = model, Content = new MyView() };
      Binding bind = new Binding { Source = model, Path = new PropertyPath("Name") };
      tab.SetBinding(TabItem.HeaderProperty, bind);
  
      Tabs.Items.Add(tab);
      Tabs.SelectedItem = tab;
  }
  </code></pre>