RaiseCanExecuteChanged事件 [英] RaiseCanExecuteChanged event

查看:778
本文介绍了RaiseCanExecuteChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正处于一个项目的阶段,该项目需要我根据各种业务规则控制启用/禁用某些超链接.我注意到有关RaiseCanExecuteChanged事件的所有主题均涉及MVVM.这是否意味着我必须使用MVVM light,或者是否可以使用标准MVVM访问此事件.如果是这样,怎么办?谢谢

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

推荐答案

ICommands 可以执行,以确定是否应该启用/禁用自己.

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.

由于必须实现ICommand,因此还必须为ViewModel(或其他取决于设计的对象)提供一种从ICommand实例外部触发此事件的方法.您如何进行此操作取决于您.根据我的经验,通常在ICommand实现上放置一个名为FireCanExecuteChanged之类的方法,您可以调用该方法来通知实例它们应该触发CanExecute事件.

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.

这是一个类似C#的伪代码的示例.

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

这篇关于RaiseCanExecuteChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆