RelayCommand和代表,试图了解代表

时间:2016-05-19 16:14:57

标签: c# delegates icommand

我需要一些帮助来了解代表是什么,以及我是否在我的程序中使用过它。我正在使用我在另一个堆栈帖子中找到的RelayCommand类来实现我的命令。

RelayCommand:

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Func<bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<bool> canExecute = null)
    {
        if (execute == null)
            throw new ArgumentNullException(nameof(execute));

        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute.Invoke();
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }
}

在我的ViewModel构造函数中,我这样做:

 public ICommand SearchCommand { get; set; }

 //Constructor
 public BookingViewModel()
 {
     SearchCommand = new RelayCommand(SearchCommand_DoWork, () => true);     
 }

 public async void SearchCommand_DoWork(object obj)
 {
  //Code inside this method not shown
 }

我知道委托是一种封装方法的类型。你可以这样写一个代表:

public delegate int MethodName(string name)

委托封装方法MethodName,返回类型为int,并接受字符串的参数。

这是否意味着在使用代码中显示的ICommand时创建了委托?封装方法是&#34; SearchCommand_DoWork&#34;

希望有人可以为我清除一些事情。

1 个答案:

答案 0 :(得分:2)

  

这是否意味着在使用代码中显示的ICommand时创建了委托?封装方法是“SearchCommand_DoWork”

您正在创建一个RelayCommand类型的新对象。正如您在类的构造函数中看到的那样,您传入一个Action对象(不返回值的委托)和一个Func对象(返回值的委托)。

对于Action委托,您传入一个封装void函数SearchCommandDoWork的对象,对于Func对象,您传入的lambda函数不带参数,并且始终返回true。

Action委托封装了您的SearchCommand_DoWork函数(委托基本上是一个类型安全函数指针)。

Action和Func都是预定义的委托。您还可以定义自己的代理,这就是

public delegate int MethodName(string name)

确实

相关问题