MVVM pattern is wonderful with MVVM Light better but sometimes I think I don't understand anything. I've a business application in SL 4 where I've, by now, 18 VM.. and mo开发者_高级运维re to write! I'm applying the pattern Laurent Bugnion used in his session at MIX11 (with SimpleIoc class).
A viewmodel is bind to a view (name it "A") but the very same viewmodel is bind to another view too (name it "B"). Viewmodel bound with view "A" is called in a standard way in the ViewModelLocator. Viewmodel bound with view B is called with a different key so to be sure they are 2 different istances. Besides they are injected with different DomainService so entities bind with controls on view are different.
The view model registers for some messages to keep track of the variation in other viewmodels it interacts, say a selection changed means the user wants to display other things in order to retrive data on DB).
The problem is if I call view A and then view B I register for the same messages 2 times so I've 2 operations on DB.
What I think correct is to dispose viewmodel bound to view A when I call view B (generally when I close view A). But I don't really know where to dispose it, when and how! Ok.. I could imagine when and how.. but WHERE?
If you're thinking I'm confused, you're right!
If I understand you correctly, you're using the same ViewModel with two different Views. You want only one copy of the VM existing at a time.
In this case, I'd probably use whatever the VM's parent is and modify something like a Mode property on the VM.
<DataTemplate x:Key="ViewA" TargetType="{x:Type local:MyViewModel}">
<TextBlock Text="I'm View A" />
</DataTemplate>
<DataTemplate x:Key="ViewB" TargetType="{x:Type local:MyViewModel}">
<TextBlock Text="I'm View B" />
</DataTemplate>
<DataTemplate DataType="{x:Type local:MyViewModel}">
<ContentControl Content="{Binding }">
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource ViewA}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Mode}" Value="2">
<Setter Property="ContentTemplate" Value="{StaticResource ViewB}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
Then to switch views, I would simply set ParentViewModel.CurrentViewModel.Mode = 2
and the View simply gets switched without changing the ViewModel.
If you want two different copies of the same ViewModel, I'd still handle the switching in the ParentViewModel using something like ParentViewModel.CurrentViewModel = ViewModelInstanceB
, and have the ViewModelInstanceB.Mode
set to 2
I wrote some examples of switching between Views here if you're interested
精彩评论