WPF ICommand

一、目的

降低代码耦合度(将低UI层和BLL层的代码耦合度),将UI层的后台代码更好的转移到BLL层中,让视图和业务逻辑分离的更好

二、使用方式

1.创建一个RelayCommand,继承ICommand接口

    public class RelayCommand : ICommand
    {
        #region Fields
        private readonly Func _canExecute;
        private readonly Action _execute;
        #endregion

        #region Constructors
        public RelayCommand(Action execute) : this(execute, null)
        {
        }

        public RelayCommand(Action execute, Func canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }
        #endregion

        #region ICommand Members
        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (_canExecute != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        public Boolean CanExecute(Object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }

        public void Execute(Object parameter)
        {
            _execute(parameter);
        }
        #endregion
    } 
    
   

2.创建一个ViewModel类,创建RelayCommand属性对象

(1)使用lambda表达式

public class ViewModelTest
    {
        public ICommand ShowMessage
        {
            get
            {
                return new RelayCommand(new Action(t =>
                {
                    if (t == null)
                        MessageBox.Show("not have param");
                    else
                        MessageBox.Show(t.ToString());
                }));
            }
        }
    } 
    
   

(2)使用函数

    public class ViewModelTest
    {

        private void UpdateNameExecute(Object parameter)
        {
            MessageBox.Show("haha");
        }

        private bool CanUpdateNameExecute(Object parameter)
        {
            return true;
        }

        public ICommand ShowMessage
        {
            get
            {
                return new RelayCommand(UpdateNameExecute, CanUpdateNameExecute);
            }
        }
    }

3.界面后台类,将ViewModel对象赋给内容上下文

 DataContext = new ViewModelTest();

4.界面绑定命名

(1)不带参数

(2)带参数

 

 

 

参考:

https://www.cnblogs.com/weiweiboqi/p/4682136.html

 

转载于:https://www.cnblogs.com/yaosj/p/10948814.html

你可能感兴趣的:(WPF ICommand)