WPF/MVVM: Opening different UserControls in same D

2019-01-29 03:35发布

问题:

I am creating an application using the DockPanel for my layout. In the 'Left' DockPanel I have setup a few links (Labels) that I would like to use to open different UserControls when a link is clicked. I want the UserControls to always open in the 'Right' DockPanel when the appropriate link is clicked.

What mechanism in WPF (using MVVM) would I use to accomplish this? Are there any examples that I can view?

回答1:

The general pattern to follow is this:

  1. Add a ContentPresenter to the place in your user interface which will host the switch-able content (the right panel of the DockPanel in your case).
  2. The visual representation of each switchable view will be represented by a user control.
  3. The data of each switch-able view will be represented by a viewModel.
  4. Bind the Content property of the ContentPresenter to a property in your view model that is of a viewModel type that represents the view E.G. BoundContent.
  5. When the link is clicked, your viewModel should react to this by changing the bound property and raising the PropertyChanged event to notify your view.
  6. For each 'view' that can be switched you will need a DataTemplate that maps each user control to each viewModel.

Rachel Lims blog contains a couple of examples which demonstrates the above:

  • Switching views in WPF/MVVM
  • Navigation with MVVM