Reputation: 11177
So I'm rather new to WPF and MVVM and I'm having an issue here with a TabControl and trying to preserve data when switching between tabs. Basically I have a TabControl inside of a view and the TabItems are dynamically loaded and removed based on user interaction. Each TabItem is a UserControl which is its own view with its own viewmodel.
Every time a TabItem is removed (not always just going to another tab, sometimes the tabs are actually removed and recreated) I am saving the instance of its viewmodel and preserving the data but I'm having trouble getting that data back when the tab is recreated. I am using a datatemplate to create the TabItems
<DataTemplate x:Key="MyView" DataType="{x:Type vm:MyViewModel}">
<uc:MyView />
</DataTemplate>
and referencing that in the TabControl.
<TabControl ItemsSource="{Binding ViewModelList, Mode=TwoWay}"
ContentTemplate="{StaticResource MyView}"
ItemTemplate="{StaticResource MyHeader}"
SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}" />
Everything works as far as the way everything is displayed but I get a new, blank version of my UserControl each time. The itemssource set to ViewModelList is exactly what it sounds like, a list of my viewmodel instances to save the state of each tab so that it can be recreated. The problem here is that the DataTemplate approach used here doesn't really give me a way to tie my viewmodel data to the new instance of the view that is being created each time a new TabItem is created.
I am not using MVVMLight or Prism but I do have a custom EventAggregator of sorts that I have tried using here. The problem I'm having with that is getting the data to the correct instance of the viewmodel at the correct time. I think part of my issue is that MyViews datacontext is being set in its codebehind constructor to a new instance of MyViewModel and it is overriding whatever else I try and pass in...
I just don't know how to fix this. I apologize for the lengthy question but I wanted to try and cover everything. If anyone needs more information let me know, thanks in advance!
Upvotes: 2
Views: 5486
Reputation: 4865
Hmm not really sure about it, but it's worth the shot. I think, if you modify your DataTemplate
like
<DataTemplate x:Key="MyView" DataType="{x:Type vm:MyViewModel}">
<uc:MyView DataContext={Binding} />
</DataTemplate>
it might work. Try it and let me know.
Ok that is odd. From MSDN
- Items - Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
[...]
- ItemsSource - Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.)
You might want to try using Items
instead.
Upvotes: 2