ICommand的实现(1)

ICommand 接口在 System.Windows.Input 命名空间内定义。它有两个方法和一个事件。

   //
   // 摘要:
   //     Occurs when changes occur that affect whether or not the command should execute.
   event EventHandler? CanExecuteChanged;

   //
   // 摘要:
   //     Defines the method that determines whether the command can execute in its current
   //     state.
   //
   // 参数:
   //   parameter:
   //     Data used by the command. If the command does not require data to be passed,
   //     this object can be set to null.
   //
   // 返回结果:
   //     true if this command can be executed; otherwise, false.
   bool CanExecute(object? parameter);
   //
   // 摘要:
   //     Defines the method to be called when the command is invoked.
   //
   // 参数:
   //   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);

只有当 CanExecute 返回 true 时才会调用 Execute 方法。如果 CanExecute 方法返回 false,则绑定控件将自动禁用。

为了知道 CanExecute 值,请侦听 CanExecuteChanged 事件,该事件可能因传递的参数而异。

ICommand 接口一般用在 MVVM 架构中,在控件中使用Command命令属性,绑定一个自定义命令“OpenCommand”,由于 OpenCommand只不过是一个 ICommand 实例,因此在加载窗口时,它将检查 CanExecute 返回值,如果它返回 true,则它将启用按钮控件并且 Execute 方法已准备好使用,否则按钮控件将被禁用。控件在使用时,可以使用CommandParameter传递参数。

<StackPanel>
    <Button Margin="10" Command="{Binding OpenCommand}" CommandParameter="ViewA">模块A</Button>
    <Button Margin="10" Command="{Binding OpenCommand}" CommandParameter="ViewB">模块B</Button>
    <Button Margin="10" Command="{Binding OpenCommand}" CommandParameter="ViewC">模块C</Button>
</StackPanel>

ICommand具体的实现类

public class MyComand : ICommand
{
    private readonly Action<object> _action;
    private readonly Func<object,bool>? _func;

    public  MyComand(Action<object> action, Func<object, bool> func)
    {
        _action = action;
        _func = func;
    }

    /// <summary>
    /// 事件处理器
    /// </summary>
    public event EventHandler? CanExecuteChanged;

    /// <summary>
    /// 能否执行 true/false
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    public bool CanExecute(object? parameter)
    {
        return _func(parameter);
    }
    /// <summary>
    /// 执行命令
    /// </summary>
    /// <param name="parameter"></param>
    /// <exception cref="NotImplementedException"></exception>
    public void Execute(object? parameter)
    {
        _action(parameter);
    }
}
View Code

在上述代码中,使用了Action和Func委托,在调用MyCommand的时候,我们需要将方法传递给Action委托,然后再执行ICommand中的Execute。关于为什么这里要使用委托,参见C#的基础知识委托的基本用法,以及学习C#的几个不同的内置委托。

 

posted @ 2024-03-22 11:12  行稳致远ac  阅读(260)  评论(0)    收藏  举报