• 关于WPF.ICommand.CanExcute


    今天看prism发现ICommand的Canexcute能自动禁用按钮Enabled大吃一惊。
    以前用的命令都是不会自己禁用的,孤陋寡闻了,查了一下:

    RoutedCommand是会自动禁用按钮的。

    如果是你的自定义命令:
    1 调用CommandManager的invalidaterequery静态方法以编程方式触发此事件:以检查所有命令是否可用,一般发生在异步调用的时候不会自动检查,因为这个事件触发一般是切换焦点切换选择项来检查,异步时,需要放在UI线程调用这个。
    2 实现

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

    One of the great parts about commands in WPF is that they know if they can currently execute or not. When they cannot execute, the control(s) that are set to execute the command will be disabled automatically.

    WPF will automatically ask all of the commands being used in your UI if they can execute. This happens at various times, such as when input focus shifts to another control, an item is selected in a list, etc. You can also programmatically trigger this to happen by calling the CommandManager’s InvalidateRequerySuggested static method.

    This beautiful system of commands automatically notifying the UI that they cannot execute only works out-of-the-box for RoutedCommands. If you simply implement ICommand and hook up, say, a Button’s Command property to reference that non-routed command, suddenly the Magical Love Machine comes to a grinding and screeching halt. Why? Because by default WPF has no idea that your custom ICommand objects exist. How would it?

    Fortunately there is an easy solution to this problem. In your ICommand implementation, you make the CanExecuteChanged event hook the CommandManager’s RequerySuggested event.

     class MyCommand : ICommand
      {
      public bool CanExecute(object parameter)
      {
      return maybeTrueOrFalse;
      }
    
      public event EventHandler CanExecuteChanged
      {
      add { CommandManager.RequerySuggested += value; }
      remove { CommandManager.RequerySuggested -= value; }
      }
    
      public void Execute(object parameter)
      {
      // Do something awesome.
      }
      }
    

    Come From:https://bbs.csdn.net/topics/340007445?list=122323

  • 相关阅读:
    Character 比较注意先要转换成字符串类型
    ibats注意
    初试体验java多线程
    解压jar
    Velocity语法--转载
    python 批量请求url
    java.lang.NoClassDefFoundError
    疑问
    sql常用语句--转载
    Spring AOP高级——源码实现(3)AopProxy代理对象之JDK动态代理的创建过程
  • 原文地址:https://www.cnblogs.com/swobble/p/12841354.html
Copyright © 2020-2023  润新知