zoukankan      html  css  js  c++  java
  • 关于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

  • 相关阅读:
    CSS中:display:none与visible:hidden的区别
    $(function(){})和$(document).ready(function(){}) 的用法
    JavaScript 全选函数的实现
    HTML:关于a标签的target属性
    CSS:给 input 中 type="text" 设置CSS样式
    JavaScript中“javascript:void(0) ”是什么意思
    Oracle数据库——数据库安全性管理
    使用JavaScript根据从后台获取来的数据打开一个新的页面
    java reflect反射---Java高级开发必须懂的
    Java 类加载机制
  • 原文地址:https://www.cnblogs.com/swobble/p/12841354.html
Copyright © 2011-2022 走看看