我有一个 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()
{
}
}
}
因为第一个错误必须处理重载方法,所以我知道我只是忽略了一些非常简单的东西。至于第二个错误,什么是更好的处理方法,因为我无法通过该属性。