WPF Custom ICommand implementation and the CanExecuteChanged event

后端 未结 2 425
耶瑟儿~
耶瑟儿~ 2021-01-05 19:14

in my WPF UI, I use RoutedCommands that I refer to in my xaml via the following code:

Command=\"viewModel:MessageListViewModel.DeleteMessagesCommand\"
         


        
2条回答
  •  春和景丽
    2021-01-05 19:58

    I very much prefer the DelegateCommand implementation of Prism for viewmodel binding (http://msdn.microsoft.com/en-us/library/ff654132.aspx). You can invoke CanExecute() on every command invoker by calling RaiseCanExecuteChanged on it.

    Simple usage example:

    public class ViewModel
    {
       public ViewModel()
       {
          Command = new DelegateCommand(x => CommandAction(), x => CanCommandAction());
       }
    
       bool state;
    
       public void ChangeState(bool value)
       {
          state = value;
          Command.RaiseCanExecuteChanged();
       }
    
       public DelegateCommand Command {get; private set;}
    
       private void CommandAction()
       {
          //do smthn
       }
    
       private bool CanCommandAction() { return true == state; }
    }
    
    //and binding as usual
    Command="{Binding Command}"
    
        

    提交回复
    热议问题