WPF implement ICommand and similar with DelegateCommand of Prism

复制代码
 public class DelCmd : ICommand
 {
     public event EventHandler CanExecuteChanged
     {
         add
         {
             CommandManager.RequerySuggested += value;
         }
         remove
         {
             CommandManager.RequerySuggested -= value;
         }
     }

     private Action<object> _execute;
     private Predicate<object> _canExecute;

     public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue)
     {
         _execute = executeValue;
         _canExecute = canExecuteValue;
     }

     public DelCmd(Action<object> executeValue) : this(executeValue, null)
     {
         _execute = executeValue;
     }

     public bool CanExecute(object parameter)
     {
         if (_canExecute == null)
         {
             return true;
         }
         return _canExecute(parameter);
     }

     public void Execute(object parameter)
     {
         _execute(parameter);
     }
 }
复制代码
复制代码
private DelCmd clearCmd;
public DelCmd ClearCmd
{
    get
    {
        if(clearCmd==null)
        {
            clearCmd = new DelCmd(ClearCmdExecuted, ClearCmdCanExecute);
        }
        return clearCmd;
    }
}

private bool ClearCmdCanExecute(object obj)
{
    return !string.IsNullOrWhiteSpace(_imagePath) && System.IO.File.Exists(_imagePath);
}

private void ClearCmdExecuted(object obj)
{
    ImagePath = string.Empty;
}
复制代码

 

WPF raises the CommandManager.RequerySuggested static event when it thinks the execution state of commands may change. This is typically done after some UI actions that may cause something to change in all bound commands. The following implementation causes WPF to call register for its own notification of re-executing CanExecute for all commands that raise the CanExecuteChange event:

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

 

posted @   FredGrit  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
历史上的今天:
2023-05-25 C++ write batch files via filstream
2023-05-25 c++ linux download file via libcurl
点击右上角即可分享
微信分享提示