Implementing “close window” command with MVVM

后端 未结 12 1699
既然无缘
既然无缘 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:13

    I personally use a very simple approach: for every ViewModel that is related to a closeable View, I created a base ViewModel like this following example:

    public abstract class CloseableViewModel
    {
        public event EventHandler ClosingRequest;
    
        protected void OnClosingRequest()
        {
            if (this.ClosingRequest != null)
            {
                this.ClosingRequest(this, EventArgs.Empty);
            }
        }
    }
    

    Then in your ViewModel that inherits from CloseableViewModel, simply call this.OnClosingRequest(); for the Close command.

    In the view:

    public class YourView
    {
        ...
        var vm = new ClosableViewModel();
        this.Datacontext = vm;
        vm.ClosingRequest += (sender, e) => this.Close();
    }
    

提交回复
热议问题