WPF ICommand

一、目的

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

二、使用方式

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

    public class RelayCommand : ICommand
    {
        #region Fields
        private readonly Func<Object, Boolean> _canExecute;
        private readonly Action<Object> _execute;
        #endregion

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

        public RelayCommand(Action<Object> execute, Func<Object, Boolean> 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;
            }
        }

        [DebuggerStepThrough]
        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<Object>(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)不带参数

<Button Width="60" Height="30" Command="{Binding ShowMessage}"/>

(2)带参数

 <Button Width="60" Height="30" Command="{Binding ShowMessage}" CommandParameter="have param"/>

参考:

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

猜你喜欢

转载自www.cnblogs.com/yaosj/p/10948814.html
WPF
今日推荐