如何在 WPF 中更改视图?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33652707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:31:55  来源:igfitidea点击:

How to change view in WPF?

c#wpfmvvm

提问by Micsto

Have some free time and wanted to try making a game in WPF. I was wondering, what is the best way of changing the view of a window? I have made a "main menu" window, with three buttons.. New Game, Continue Game and Exit Game. When pressing New Game I want the window to go to next "viewstate" for creation of player and such, dont want a new window to pop up. Whats the best way of implementing that.

有一些空闲时间,想尝试用 WPF 制作游戏。我想知道,改变窗口视图的最佳方法是什么?我制作了一个“主菜单”窗口,带有三个按钮.. 新游戏、继续游戏和退出游戏。当按下新游戏时,我希望窗口转到下一个“视图状态”以创建玩家等,不希望弹出新窗口。什么是最好的实现方式。

回答by StepUp

It is appropriate to use DataTemplates if you want to dynamically switch Views depending on the ViewModel:

如果你想根据 ViewModel 动态切换 View,那么使用 DataTemplates 是合适的:

<Window>
   <Window.Resources>
      <DataTemplate DataType="{x:Type ViewModelA}">
         <localControls:ViewAUserControl/>
      </DataTemplate>
      <DataTemplate DataType="{x:Type ViewModelB}">
         <localControls:ViewBUserControl/>
      </DataTemplate>
   <Window.Resources>
  <ContentPresenter Content="{Binding CurrentView}"/>
</Window>

If Window.DataContextis an instance of ViewModelA, then ViewAwill be displayed and

如果Window.DataContext是 的实例ViewModelAViewA则将显示并

Window.DataContextis an instance of ViewModelB, then ViewB will be displayed.

Window.DataContext是 ViewModelB 的一个实例,那么就会显示 ViewB。

The best example I've ever seen and read it is made by Rachel Lim. See the example.

我见过和读过的最好的例子是Rachel Lim 制作的请参阅示例

回答by Dom84

You could implement every gui you need as an UserControl and load the needed UserControl depending on your current step.

您可以将您需要的每个 gui 实现为 UserControl 并根据您当前的步骤加载所需的 UserControl。