0
votes

Lets say I have a MainWindow and in it one Grid Column where i place my UserControl. And the user can switch the usercontrol in this column with a button click, a tab or a menuItem.

I have 3 userControls : UserControl1, UserControl2 , USerControl3 3 ViewModels : UserControl1ViewModel, UserControl2ViewModel, UserControl3ViewModel a MainWindow and a MainWindowViewModel

Lets say that in this column the default userControl is the UserControl1. How do I switch it with a Button click to UserControl2.

I found some resources like this :

 <Window.Resources>
   <DataTemplate DataType="{x:Type vm:UserControl1ViewModel}">
      <v:UserControl1 />
   </DataTemplate>
   <DataTemplate DataType="{x:Type vm:UserControl2ViewModel}">
      <v:UserControl1 />
   </DataTemplate>
   <DataTemplate DataType="{x:Type vm:UserControl3ViewModel}">
      <v:UserControl3/>
   </DataTemplate>
</Window.Resources>

The idea is to somehow bind a Command to Button or MenuItem to switch the UserControls. That code is going to be handled in MainWindowViewModel.

1

1 Answers

1
votes

In your MainViewModel create a property to hold the displayed ViewModel as follows

    private Object _DisplayedViewModel;

    public Object DisplayedViewModel
    {
        get { return _DisplayedViewModel; }
        set
        {
            _DisplayedViewModel = value;
            // Your INotifyPropertyChanged notification
            //RaisePropertyChanged("DisplayedViewModel");
        }
    }

In MainWindow.xaml, bind DisplayedViewModel to the frame content.

<Frame Content="{Binding DisplayedViewModel}" NavigationUIVisibility="Hidden"/>

For the button command binding

    private ICommand _ShowUC2;

    public ICommand ShowUC2
    {
        get {
            if (_ShowUC2 == null)
            {
                _ShowUC2 = new RelayCommand() =>
                {
                    DisplayedViewModel = new UserControl2ViewModel();
                };
            }
            return _ShowUC2; }
    }

Assuming your VMs are wired properly, setting the DisplayedViewModel to any of the three UserControlViewModel reference will cause the respective UserControl to be displayed in the frame.