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