Implementing “close window” command with MVVM

后端 未结 12 1708
既然无缘
既然无缘 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 10:09

    first of all give your window a name like

    x:Name="AboutViewWindow"
    

    on my close button I've defined Command and Command Parameter like

    CommandParameter="{Binding ElementName=AboutViewWindow}"
    Command="{Binding CancelCommand}"
    

    then in my view model

    private ICommand _cancelCommand;        
    public ICommand CancelCommand       
    {
       get          
         {
            if (_cancelCommand == null)
               {
                  _cancelCommand = new DelegateCommand(
                        x =>
                        {
                            x?.Close();
                        });
                }
    
                return _cancelCommand;          
         }      
    }
    

提交回复
热议问题