Change the User Control of a Window dynamically in WPF (MVVM)

后端 未结 1 778
时光说笑
时光说笑 2021-02-04 21:32

I\'m new with WPF and I was just doing a simple menu using MVVM with bindings and commands but I think I\'m d

1条回答
  •  时光说笑
    2021-02-04 22:13

    I think the problem is that you are trying to change the Content property of ContentControl, not the property of your ViewModel. You have connected your ViewModel to the host ControlPanel, but also you need the separate view models for user controls that will be hosted there. I've added class for user control view model and changed host's view model property name for the clarity sake. Correct your code as follows.

    //host view model
    class MainModel : ViewModelBase
    {
        private UserControl _content;
    
        public MainModel() { }
    
        internal void SetNewContent(UserControl _content)
        {
            ContentWindow = _content;
        }
    
        public UserControl ContentWindow
        {
            get { return _content; }
            set
            {
                _content = value;
                OnPropertyChanged("ContentWindow");
            }
        }
    }
    
    //user contol's view model
    class MenuViewModel : ViewModelBase
    {
        MainModel _mainModel;
        RandomModel _model; // 
    
        public ICommand OpenUsersCommand { get; private set; }
    
    
        public MenuViewModel(MainModel mainModel, RandomModel model )
        {
            this._mainModel = mainModel;
            this._model = model;
            OpenUsersCommand = new RelayCommand(OpenUsers, CanOpenUsers);
        }
    
        private void OpenUsers(object _param)
        {
            UsersPanelViewModel upmodel = new UsersPanelViewModel(_mainModel, _model);
            UsersPanel up = new UsersPanel();
            up.DataContext = upmodel;
            _mainModel.SetNewContent(up);
        }
    
        private bool CanOpenUsers(object _param)
        {
            return true;
        }
    }
    
        //main window function
        public ControlPanel()
        {
            InitializeComponent();
    
            //create main view model for host
            MainModel mainModel = new MainModel();
    
            RandomModel model = new RandomModel(); //
    
            //create view model for user controls
            MenuViewModel viewmodel = new MenuViewModel(mainModel, model);
            ButtonsMenu bm = new ButtonsMenu(); // 
            bm.DataContext = viewmodel;
    
            //set host's property in our user control
            mainModel.ContentWindow = bm;
            this.DataContext = mainModel;
        }
    

    main window XAML

    
        
            
        
    
    

    Hope it's quite understandable.

    0 讨论(0)
提交回复
热议问题