zoukankan      html  css  js  c++  java
  • WPF在ViewModel中绑定按钮点击(CommandBase定义)

    定义CommandBase

    public class CommandBase:ICommand
        {
            private readonly Action<object> _commandpara;
            private readonly Action _command;
            private readonly Func<bool> _canExecute;
    
            public CommandBase(Action command, Func<bool> canExecute=null)
            {
                if(command==null)
                {
                    throw new ArgumentNullException();
                }
                _canExecute = canExecute;
                _command = command;
            }
    
            public CommandBase(Action<object> commandpara,Func<bool> canExecute=null)
            {
                if(commandpara==null)
                {
                    throw new ArgumentNullException();
                }
                _canExecute = canExecute;
                _commandpara = commandpara;
            }
    
            public bool CanExecute(object parameter)
            {
                return _canExecute == null || _canExecute();
            }
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
            
            public void Execute(object parameter)
            {
                if (parameter != null)
                {
                    _commandpara(parameter);
                }
                else
                {
                    if (_command != null)
                    {
                        _command();
                    }
                    else if (_commandpara != null)
                    {
                        _commandpara(null);
                    }
                }
            }
        }

    xaml绑定(带参/不带参)

    <Button Command="{Binding CreateButtonCommand}"/>
    <Button Command="{Binding CreateButtonCommand}" CommandParameter="参数"/>

    ViewModel定义(带参/不带参)

    public ICommand CreateButtonCommand { get { return new CommandBase(CreateButton); } }
            private void CreateButton()
            {
                // Command逻辑
            }
            private void CreateButton(object o)
            {
                // Command逻辑
            }
  • 相关阅读:
    新博客即将启用
    关于博主 | 联系博主
    结束吧,为这不圆满的故事划上一个残缺的句号
    自用线段树模板
    NOIP 2017 day 1 游记
    NOIP 2017 Day 0. 游记
    NOIP 2017 day -1 杂记
    再一次想不出应该起什么标题
    做图与树做到吐的一天
    自用二分图匹配模板
  • 原文地址:https://www.cnblogs.com/zbfamily/p/6380765.html
Copyright © 2011-2022 走看看