WPF Custom ICommand implementation and the CanExecuteChanged event

大憨熊 提交于 2019-11-30 05:24:08

问题


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

Command="viewModel:MessageListViewModel.DeleteMessagesCommand"

I don't like this static link to my ViewModel class,I think this is not as nice as creating a custom ICommand implementation and use a syntax like the following

Command="{Binding DeleteMessagesCommand}"

Having created one, I notice one major drawback of what I've done: RoutedCommands utilize the CommandManager and (in some way that is completely opaque to me) fire the CommandManager.RequerySuggested event, so that their CanExecute Method is requeried automatically. As for my custom implementation, CanExecute is only fired once at startup and never again after that.

Does anybody have an elegant solution for this?


回答1:


Just implement the CanExecuteChanged event as follows:

public event EventHandler CanExecuteChanged
{
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

When you assign the command to a control, it subscribes to the CanExecuteChanged event. If you "redirect" it to the CommandManager.RequerySuggested event, the control will be notified whenever CommandManager.RequerySuggested is triggered.




回答2:


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<object>(x => CommandAction(), x => CanCommandAction());
   }

   bool state;

   public void ChangeState(bool value)
   {
      state = value;
      Command.RaiseCanExecuteChanged();
   }

   public DelegateCommand<object> Command {get; private set;}

   private void CommandAction()
   {
      //do smthn
   }

   private bool CanCommandAction() { return true == state; }
}

//and binding as usual
Command="{Binding Command}"


来源:https://stackoverflow.com/questions/3768301/wpf-custom-icommand-implementation-and-the-canexecutechanged-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!