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逻辑
            }
  • 相关阅读:
    JavaScript对象继承的实现
    Redis资料
    Difference between LINQ to SQL and the Entity Framework
    闭包,懂不懂由你,反正我是懂了
    Castle资料
    csu 1242 碱基配对
    csu 1242 碱基配对——一个错误的解答
    [转载]zoj 分类
    计算素数
    魔方阵
  • 原文地址:https://www.cnblogs.com/zbfamily/p/6380765.html
Copyright © 2011-2022 走看看