DelegateCommand的重载方法

时间:2013-03-08 02:24:15

标签: c# mvvm properties overloading delegatecommand

我有一个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()
        {

        }
    }
}

因为第一个错误必须处理重载方法,所以我知道我只是忽略了一些非常简单的事情。至于第二个错误,处理它的更好方法是因为我无法传递该属性。

1 个答案:

答案 0 :(得分:3)

DelegateCommand的构造函数已配置为Action<object>而不是您传递ICommand实例。

你应该用应该发生的行动来构建。例如,我认为你的意思是调用“ExportList”:

_exportCommand = new DelegateCommand((o) => this.ExportList());

注意:因为ExportList实际上没有对象参数,所以您需要使用匿名方法进行调用。

相关问题