WPF 定义Command
Posted 唐宋元明清的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF 定义Command相关的知识,希望对你有一定的参考价值。
直接上代码:
public class LoginDelegateCommand : ICommand { private Action _execute; private Predicate<object> _canExecute; public LoginDelegateCommand([NotNull]Action execute): this(execute, DefaultCanExecute) { } public LoginDelegateCommand([NotNull]Action execute, Predicate<object> canExecute) { this._execute = execute ?? throw new ArgumentNullException("execute"); this._canExecute = canExecute ?? throw new ArgumentNullException("canExecute"); } public bool CanExecute(object parameter) { return this._canExecute != null && this._canExecute(parameter); } public void Execute(object parameter) { UserLoginHelper.NotifyToLoginWindow(() => { this._execute(); }); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; this.CanExecuteChangedInternal += value; } remove { CommandManager.RequerySuggested -= value; this.CanExecuteChangedInternal -= value; } } private event EventHandler CanExecuteChangedInternal; public void OnCanExecuteChanged() { EventHandler handler = this.CanExecuteChangedInternal; handler?.Invoke(this, EventArgs.Empty); } private static bool DefaultCanExecute(object parameter) { return true; } }
在viewmodel中,定义一个Command属性
Command=new LoginDelegateCommand (()={添加逻辑});
然后绑定即可。
以上是关于WPF 定义Command的主要内容,如果未能解决你的问题,请参考以下文章