命令为视图提供了一种机制来更新 MVVM 架构中的模型。命令提供了一种在元素树中搜索命令处理程序的方法。ICommand 接口在 System.Windows.Input 命名空间内定义。它有两个方法和一个事件。
只有当 CanExecute 返回 true 时才会调用 Execute 方法。如果 CanExecute 方法返回 false,则绑定控件将自动禁用。
为了了解 CanExecute 值,请收听 CanExecuteChanged 事件,该事件可能因传递的参数而异。
使用代码
ICommand 的使用
ICommand接口一般用在MVVM架构中。在 Button 控件中,Command 属性绑定到“SearchCommand”。由于 SearchCommand只不过是一个 ICommand 实例,因此在加载窗口时,它将检查 CanExecute 返回值,如果返回 true,则它将启用按钮控件并且 Execute 方法已准备好使用,否则按钮控件将被禁用。
<Button Width= "100" Height= "20" HorizontalAlignment= "Center" Grid.Row= "1" Content= "Update" Command= "{Binding Path=SearchCommand}" />
在ViewModel中定义命令自动属性:
public ICommand SearchCommand { get; set; }
接下来在构造方法中初始化命令绑定方法
public ViewModel()
{
SearchCommand = new RelayCommand(Search);
}
RelayCommand 是命令接口类实现:
public class RelayCommand : ICommand
{
#region Private Members
/// <summary>
/// The _action to run
/// </summary>
private Action _action;
#endregion
#region Constructor
/// <summary>
/// Default constructor
/// </summary>
public RelayCommand(Action action)
{
_action = action;
}
#endregion
#region Command Methods
/// <summary>
/// A relay command can always execute
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return true;
}
/// <summary>
/// Executes the commands Action
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
_action();
}
#endregion
#region Public Events
/// <summary>
/// The event thats fired when the <see cref="CanExecute(object)"/> value has changed
/// </summary>
public event EventHandler CanExecuteChanged = (sender, e) => { };
#endregion
}
最后是命令绑定实现搜索方法
public void Search()
{
Console.WriteLine("方法测试");
}