MVVM WPF change smoothly one window to another

2019-08-17 04:22发布

I'm doing an app in WPF with design pattern MVVM. I have there fullsize windows(not only maximized but fullsize).

I need to switch one window to another(open window B by pressing button x in window A and close window A when window B is showns).

I'm closing window A in loaded event in window B but I still can see a desktop for a while before window B is shown.

How to do it without seeing desktop?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-08-17 04:58

You can make 2 separate user controls and put the content of each window inside a user control.

inside your main window you define data templates those will decide what is the view to be used based on the current Datacontext

<Window.Resources>
<DataTemplate DataType="{x:Type viewmodels:viewmodel1}" >
     <views:Usercontrol1/>
</DataTemplate>

<DataTemplate DataType="{x:Type viewmodels:viewmodel2}" >
    <views:Usercontrol2/>
</DataTemplate>
</Window.Resources>

Then you create a MainViewModel and define currentviewmodel viewmodel1and viewmodel2 and a command that will change the currentviewmodel and after that set the Datacontext of your MainWindow to the MainViewModel.

in your MainWindow you bind your button to that command, and then you just make the command change the currentviewmodel and inside your MainWindow

<Button Content="change grid data context" Command="{Binding yourCommand}"/>
<Grid DataContext="{Binding currentviewmodel}"/>

you don't worry about which view to use, when the DataContext get set the DataTemplates defines which view to use

查看更多
我只想做你的唯一
3楼-- · 2019-08-17 05:11

Instead of switching between windows, you can have one window with a ContentControl. All you'll need to do is change its Content property to switch between views.

I also recommend having a look at the Prism library which has this kind of functionality built in, and specifically its navigation documentation.

查看更多
登录 后发表回答