重载的DelegateCommand方法
本文关键字:方法 DelegateCommand 重载 | 更新日期: 2023-09-27 18:02:58
我有一个DelegateCommand类,其中有2个构造函数。当我将我的属性传递给该类的构造函数时,我得到一条错误消息,上面写着:
Error 1 The best overloaded method match for 'QMAC.ViewModels.DelegateCommand.DelegateCommand(System.Action<object>)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'System.Windows.Input.ICommand' to 'System.Action<object>'
对于我的DelegateCommand,下面是我所拥有的(没有注释以保持简短):
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
namespace QMAC.ViewModels
{
class DelegateCommand : ICommand
{
private Action<object> _execute;
private Predicate<object> _canExecute;
public DelegateCommand(Action<object> execute) : this(execute, null)
{
}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute.Equals(null))
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
下面是我要传递的属性和函数:
using QMAC.Models;
using System;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Text;
using System.Windows.Input;
using System.Windows.Threading;
namespace QMAC.ViewModels
{
class MainViewModel: ViewModelBase
{
Address address;
Location location;
private string _locationPicked;
private string _ipAddress;
private DelegateCommand _exportCommand;
public MainViewModel()
{
address = new Address();
location = new Location();
_ipAddress = address.IPAddress;
_exportCommand = new DelegateCommand(ExportCommand);
}
public ICommand ExportCommand
{
get { return _exportCommand; }
}
public void ExportList()
{
}
}
}
因为第一个错误必须处理一个重载方法,我知道我只是忽略了一些非常简单的东西。至于第二个错误,有什么更好的方法来处理呢?因为我不能传递那个属性。
您的DelegateCommand
的构造函数被配置为取Action<object>
而不是传递ICommand
实例。
你应该构建应该发生的动作。例如,我认为你的意思是调用"ExportList":
_exportCommand = new DelegateCommand((o) => this.ExportList());
注意:因为ExportList实际上没有一个对象参数,所以你需要使用一个匿名方法来进行调用。