First, the purpose
Code decrease the degree of coupling (coupling code UI layer and low layer BLL), the better the code behind the UI layer is transferred to the BLL layer, and the view to better business logic
Second, use
1. Create a RelayCommand, inherited ICommand interface
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. Create a ViewModel class, create an object property RelayCommand
(1) using a lambda expression
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) using the function
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. Background class interface, the contents of the context object is assigned ViewModel
DataContext = new ViewModelTest();
4. binding interface named
(1) without parameters
<Button Width="60" Height="30" Command="{Binding ShowMessage}"/>
(2) with parameters
<Button Width="60" Height="30" Command="{Binding ShowMessage}" CommandParameter="have param"/>
reference:
https://www.cnblogs.com/weiweiboqi/p/4682136.html