Load multiple UserControls on WPF window

2020-05-08 08:22发布

问题:

I have a Window on which I load an UserControl say Control1. Now if the user clicks on a certain button a new UserControl, Control2 should be loaded on the Window and Control1 should dissapear. Same here, when a user clicks a button the next UserControl, Control3 should be loaded and Control2 should dissapear. It should be possible to go back too, e.g. from Control3 to Control2.

Loading the first main UserControl on my Window was easy, I've done that more than enough. But I'm stuck at how to implement the 'navigation' between the Usercontrols. Never done anything like that before. I use MVVM for my WPF app. Anyone some ideas?

Thx.

Edit: With Rachel's answer I now do this in a command to switch the controls: In the MainWindow:

<DataTemplate DataType="{x:Type ViewModel:MainControlViewModel}">
<my:MainControl />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:ProductsControlViewModel}">
<my:ProductsControl />
</DataTemplate>


 <Grid>
<ContentControl Content="{Binding CurrentPageViewModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>

In the MainControlViewModel and nearly the same in the ProductsControl:

 public ICommand LoadProductControlCommand
{
  get
  {
    if (_loadProductControl == null)
      _loadProductControl = new RelayCommand(LoadProductControl);
    return _loadProductControl;
  }
}

private void LoadProductControl(object notUsed)
{
  _mainWindowViewModel = (MainWindowViewModel) Application.Current.MainWindow.DataContext;
  _mainWindowViewModel.CurrentPageViewModel = new ProductsControlViewModel();
}

Is this a good way or should I do it different? Because in my app the buttons are on the controls and not the main window.

回答1:

Put a ContentPresenter in the MainWindow like this:

<ContentPresenter Content="{Binding ActiveWidget}"/>

and then in the ViewModel

public ViewModelBase ActiveWidget {get;set;} // Don't forget INotifyPropertyChanged!!

then you must create a DataTemplate for each ViewModel with an appropiate instance of the UserControls. See This Article for a generic solution to this.



回答2:

Rachel's comment helped me to find the solution.