开发者

RaiseCanExecuteChanged event

I am at the stage in a project where I need to get control of enabling / disabling 开发者_C百科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


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); }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜