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逻辑 }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM