title: TabControl and MVVM
body: <p>I am having difficulties in making TabControl run flawlessly in MVVM architecture. Currently what I am doing is having TabControl's ItemsSource property bound to ObservableCollection Screens property. Each time I want to add new tab, I create adequate ViewModel, add it to Screens, and throuh data templates adequate View will be shown.</p>
  
  <p>Problems:</p>
  
  <p>1) it seems that desctructor for my ViewModels are not fired until complete application closes. I am not sure if Data templates are the cause of this. When I remove ViewModel from Screens collection, it should be available for GC, since all I did was added it to Screens collection, which showed the View, and then when command to close the view was issued, I removed from collection. After that I tried to force Gc.Collect, but still dctor fires only on application close. I am not sure why is this happening...</p>
  
  <p>1) in some data structures it is not possible to bind to ViewModel's property through ElementName, so one way around is to use RelativeSource binding. However, this creates lots of binding exceptions when element (ex View) is being closed. Similar problem to mine is described here:</p>
  
  <p><a href="https://stackoverflow.com/questions/11474351/how-to-avoid-binding-error-when-parent-is-removed">How to avoid Binding Error when parent is removed</a></p>
  
  <p>In my case TargetNullValue and FallbackValue do not help, and the only way around I have found is to have ViewModel as StaticResource. Problem with this approach is that when using Screens collection and data templates to connect Views and ViewModels, you cannot create viewmodels the usual way:</p>
  
  <pre><code>&lt;UserControl.Resources&gt;
      &lt;vm:SomeViewModel x:Key="someViewModel" /&gt;
  &lt;/UserCpntrol.Resources&gt;
  </code></pre>
  
  <p>So, is there an alternative approach to using TabControl in MVVM scenario, or I am doing something wrong here?</p>