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

  • 相关阅读:
    VS2012 for SharePoint2013 Tool安装
    SharePoint 2013网站管理网站策略(关闭和删除策略)
    呼风唤雨的公交
    ASP、Access、80040e14、保留关键字、INSERT INTO 语句的语法错误
    表格边框设置
    DotNet开发中关于SQLServer连接的两种方法之比较
    SQL语句集锦
    动态网页设计笔记
    SQL SERVER中日期 where 问题的解决
    配置你的ASP.NET运行环境
  • 原文地址:https://www.cnblogs.com/swobble/p/12841354.html
Copyright © 2011-2022 走看看