RaiseCanExecuteChanged event

女生的网名这么多〃 提交于 2019-12-25 16:04:27

问题


I am at the stage in a project where I need to get control of enabling / disabling some hyperlinks based on various business rules. I noticed all topics on RaiseCanExecuteChanged event refer to MVVM light. Does this mean that I have to use MVVM light or is there a way to access this event using standard MVVM. If so, how? Thanks


回答1:


ICommands have an event that command watchers subscribe to. When this event fires, it is the responsibility of the watchers (Button, etc) to call CanExecute in order to determine if they should enable/disable themselves.

As you must implement ICommand, you must also provide a way for your ViewModels (or whatever, depending on your design) to fire this event from outside the ICommand instance. How you go about this is up to you. It is common (in my experience) to place a method on your ICommand implementation called something like FireCanExecuteChanged which you can call to inform the instance that they should fire the CanExecute event.


Here's an example in vaguely c#-like pseudocode.

public sealed class MyViewModel
{
  // dependencyproperty definition left off for brevity

  public MyCommand ACommand {get;private set;}

  // fired when some DP changes which affects if ACommand can fire    
  private static void OnSomeDependencyPropertyChanged
      (object sender, EventArgs e)
  {
    (sender as MyViewModel).ACommand.FireCanExecuteChanged();
  }
}

public sealed class MyCommand : ICommand
{
  public event EventHandler CanExecuteChanged;
  public bool CanExecute(object arg) { return arg != null; }
  public void Execute(object arg) { throw new NotImplementedException(); }
  public void FireCanExecuteChanged() { 
                  CanExecuteChanged(this, EventArgs.Empty); }
}


来源:https://stackoverflow.com/questions/6048460/raisecanexecutechanged-event

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