let's see an instance that is easily and can run well
public class OpenChildWindowCommand : ICommand { /// <summary> /// 当出现影响是否应执行该命令的更改时发生。 /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// 定义用于确定此命令是否可以在其当前状态下执行的方法。 /// </summary> /// <param name="para"></param> /// <returns></returns> public bool CanExecute(object para) { if (para != null) { CanExecuteChanged(para, new EventArgs()); } return true; //return false; } /// <summary> /// 定义在调用此命令时调用的方法。 /// </summary> /// <param name="para"></param> public void Execute(object para) { MessageBox.Show("afdafd"); } }
and in xaml
<UserControl.Resources> <dat:OpenChildWindowCommand x:Key="kk"></dat:OpenChildWindowCommand> </UserControl.Resources> <Button Grid.Row="2" Margin="0,0,4,0" Height="40" Width="40" Command="{StaticResource kk}" />
and now you click this button you will see the messagebox.
In order to understand the ICommand
let's see it
public interface ICommand { // Summary: // Occurs when changes occur that affect whether the command should execute. event EventHandler CanExecuteChanged; // Summary: // Defines the method that determines whether the command can execute in its // current state. // // Parameters: // parameter: // Data used by the command. If the command does not require data to be passed, // this object can be set to null. // // Returns: // true if this command can be executed; otherwise, false. bool CanExecute(object parameter); // // Summary: // Defines the method to be called when the command is invoked. // // Parameters: // parameter: // Data used by the command. If the command does not require data to be passed, // this object can be set to null. void Execute(object parameter); }
Now it's clearly
if we want to set the method to the model first we need construct the class like below
public class CommandHandler:ICommand { Action<object> _act; bool _canExecute; public CommandHandler(Action<object> act, bool canExecute) { _act = act; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _act(parameter); } }
and now in our model class
private ICommand _SaveCommand; public ICommand SaveCommand { get { return _SaveCommand = new CommandHandler(Save, _Execute); } } #endregion private void Save(object param) { ObservableCollection<Employee> newIM = new ObservableCollection<Employee>(); foreach (Employee e in newIM) { string a = e.FirstName; string b = e.LastName; } or othething }