Note that there are some explanatory texts on larger screens.

plurals
  1. POBinding TabControl ItemsSource to an ObservableCollection of ViewModels causes content to refresh on focus
    text
    copied!<p>I'm creating an WPF application using the MVVM framework, and I've adopted several features from Josh Smith's article on MVVM <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="nofollow noreferrer">here...</a> </p> <p>Most importantly, I'm binding a TabControl to an ObservableCollection of ViewModels. This means that am using a tabbed MDI interface that displays a UserControl as the content of a TabItem. The issue I'm seeing in my application is that when I have several tabs and I flip back and forth between tabs, the content is being refersh each time I change tabs. </p> <p>If you download Josh Smith's source code, you'll see that his app has the same problem. For example, click on the "View All Customers" button and scroll down to the bottom the ListView. Next click on the "Create New Customer" button. When you switch back to the All Customer view you'll notice that the ListView scrolls back to the top. If you switch back to the New Customer tab and place your cursor in one of the TextBoxes, then switch to All Customers tab and back, you'll notice that the cursor is now gone.</p> <p>I imagine that this is because I'm using an ObservableCollection, but I can't be sure. Is there any way to prevent the tab's content from refreshing when it receives the focus?</p> <p><strong>EDIT:</strong> I found my problem when I ran the profiler on my application. I'm defining a DataTemplate for my ViewModels so it knows how to render the ViewModel when it is displayed in the tab... like so:</p> <pre><code>&lt;DataTemplate DataType="{x:Type vm:CustomerViewModel}"&gt; &lt;vw:CustomerView/&gt; &lt;/DataTemplate&gt; </code></pre> <p>So whenever I switch to a different tab, it has to re-create the ViewModel again. I fixed it temporarily by changing my ObservableCollection of ViewModels to an ObservableCollection of UserControls. However, I would really still like to use DataTemplates if possible. Is there a way to make a DataTemplate work?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload