Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change view in WPF?

Tags:

c#

mvvm

wpf

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.

like image 777
Micsto Avatar asked Dec 10 '22 20:12

Micsto


1 Answers

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

<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.DataContext is an instance of ViewModelA, then ViewA will be displayed and

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

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

like image 76
StepUp Avatar answered Dec 21 '22 21:12

StepUp