Implementing “close window” command with MVVM

后端 未结 12 1709
既然无缘
既然无缘 2020-12-05 09:31

So my first attempt did everything out of the code behind, and now I\'m trying to refactor my code to use the MVVM pattern, following the guidance of the MVVM in the box inf

12条回答
  •  醉话见心
    2020-12-05 10:00

    This is taken from ken2k answer (thanks!), just adding the CloseCommand also to the base CloseableViewModel.

    public class CloseableViewModel
    {
        public CloseableViewModel()
        {
            CloseCommand = new RelayCommand(this.OnClosingRequest);
        }
    
        public event EventHandler ClosingRequest;
    
        protected void OnClosingRequest()
        {
            if (this.ClosingRequest != null)
            {
                this.ClosingRequest(this, EventArgs.Empty);
            }
        }
    
        public RelayCommand CloseCommand
        {
            get;
            private set;
        }
    }
    

    Your view model, inherits it

    public class MyViewModel : CloseableViewModel
    

    Then on you view

    public MyView()
    {
        var viewModel = new StudyDataStructureViewModel(studyId);
        this.DataContext = viewModel;
    
        //InitializeComponent(); ...
    
        viewModel.ClosingRequest += (sender, e) => this.Close();
    }
    

提交回复
热议问题