开发者

How can I switch views between viewmodels?

开发者 https://www.devze.com 2023-03-31 17:15 出处:网络
My Main window defines the markup for the application, for this s开发者_C百科pecific scenario lets say I have a grid with 2 columns.

My Main window defines the markup for the application, for this s开发者_C百科pecific scenario lets say I have a grid with 2 columns.

First column will have navigation links, and second column will display the different views.

There are 2 views (and 2 viewmodels) defined in mainwindow xaml:

<Window.Resources>       
   <DataTemplate DataType="{x:Type vm:Window1ViewModel}">
       <vw:Window1View/>
   </DataTemplate>
   <DataTemplate DataType="{x:Type vm:Window2ViewModel}">
       <vw:Window2View/>
   </DataTemplate>      
</Window.Resources>

And in second grid column that displays the views i got :

<ContentControl  Content="{Binding Path=ViewModel}" HorizontalAlignment="Left">                    
</ContentControl>

Where ViewModel is a property that I set accordingly to a view(viewmodel) that i want to display.

Like :

ViewModel = new Window1ViewModel();

(datacontext of the mainwindowview is set to MainWindowViewModel)

So there is no problem to switch between views from the MainWindowViewModel.

My problem is how to switch within Window1ViewModel into Window1ViewMode2?

The various ViewModels don't "know" about other ViewModels.

Only MainWindowViewModel knos about others...

How can I solve this? Maybe I should define a custom Event (with parameter), MainWindowViewModel will subscribe and other viewmodels will trigger it and then MainWindowViewModel will switch to the needed view?


the solution you describe is one possibility. One other I can think of is using some kind of Navigation-Service (static class or interface you pass to all your child-Viewmodels) that do this kind of work.

If your MainWindowViewModel creates all the others I would stick to the interface solution. You can for example let the MainWindowVM implement such a interface and inject it into all the child-vm on creation. This is much the same as your event-approach but instead of the childs-providing and the main having to subscribe you have the main give something ... IMHO the better approach.


Ok, may be I understood your point. You want that controller actually be modelview which notifies to mainmodelview about the fact that it have to be swapped with someone else.

Considering that we are talking about WPF, create DependecyProperty on mainmodelview , and set it from childview, which in code behind will trigger modelviews swap.

0

精彩评论

暂无评论...
验证码 换一张
取 消