how to dynamically change userControl on button (click) present in the usercontrol in wpf MVVM light

前端 未结 2 489
难免孤独
难免孤独 2020-12-15 13:38

I have a Main Window that host Usercontrol as ContentControl host.What i want is, to dynamically change usercontrol on button click(present in the first Usercontrol ) to an

2条回答
  •  粉色の甜心
    2020-12-15 14:24

    In your MainViewModel make a property eg "DisplayViewModel" with the basetype of your vm1 and vm2.

    private MyViewModelBase _displayViewModel;
    
    public MyViewModelBase DisplayViewModel
    {
        get { return _displayViewModel; }
        set 
        { 
            _displayViewModel = value;
            OnPropertyChanged("DisplayViewModel"); // Raise PropertyChanged
        }
    }
    

    In your MainView.xaml insert a ContentControl which binds to the DisplayViewModelProperty :

    
    

    On your Button-Command you can Modify the DisplayProperty via Setter with another ViewModel and in combination with your DataTemplates the UserControl displayed by the ContentControl should change to the View according to the newly set ViewModel-Type.

    private void MyButtonCommand()
    {
        DisplayViewModel = new ViewModel2();
    }
    

提交回复
热议问题