Binding TabControl ItemsSource to an ObservableCollection of ViewModels causes content to refresh on

Posted by Brent on Stack Overflow See other posts from Stack Overflow or by Brent
Published on 2010-05-05T03:14:17Z Indexed on 2010/05/08 15:48 UTC
Read the original article Hit count: 1021

I'm creating an WPF application using the MVVM framework, and I've adopted several features from Josh Smith's article on MVVM here...

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.

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.

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?

EDIT: 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:

<DataTemplate DataType="{x:Type vm:CustomerViewModel}">
    <vw:CustomerView/>
</DataTemplate>

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?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about mvvm