天天看点

wpf自定义命令与启用/禁用控制

wpf自定义命令的资料网上很多,但基本上都是简单提一下,想再深入一点总觉得差一点,例如今天我就碰到这样的问题,自定义命令没问题,网上一搜复制粘贴,搞定,但我要是想用个checkbox控制它生不生效怎么弄呢?没问题,现成的就有,引一个prism,示例程序里就有,但一个命令引一个框架不太至于。

其实网上说的已经完成了一大半了,例如下面的:

class CustomCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object,bool> _canExecute;

        public CustomCommand(Action<object> execute)
            : this(execute, null)
        {
        }
        public CustomCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _canExecute = canExecute;
            _execute = execute;
        }

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

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
           

使用:

public CustomCommand StartAndStopCommand { get; set; }
        public MainViewModel()
        {
            StartAndStopCommand = new CustomCommand(p => { }, p =>
            {
                return true;
            });
        }
           

这里的canexecute直接返回true,命令一直生效。但要控制它的是否启用这里得改,改成这样

public CustomCommand StartAndStopCommand { get; set; }
public bool canuse=false;
        public MainViewModel()
        {
            StartAndStopCommand = new CustomCommand(p => { }, p =>
            {
                return canuse;
            });
        }
           

看着没毛病,里面返回变量值,外面控制一下这个变量就可以实现了,但,真的是这样吗?运行之后发现并不是,不管外面怎么改canuse的值,都控制不了命令的是否启用。

原因很简单,canexecute不知道它的enable改变了,仔细看代码我们会发现命令的CanExecuteChanged我们只是定义了,并没用到,改成下面就可以了

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

一下是命令所有代码:

class CustomCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object,bool> _canExecute;

        public CustomCommand(Action<object> execute)
            : this(execute, null)
        {
        }
        public CustomCommand(Action<object> execute, Func<object, bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _canExecute = canExecute;
            _execute = execute;
        }

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

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

        public void Execute(object parameter)
        {
            _execute(parameter);
        }
    }
           

用法不变。