首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DelegateCommand的重载方法

DelegateCommand的重载方法
EN

Stack Overflow用户
提问于 2013-03-08 10:24:15
回答 1查看 3.3K关注 0票数 0

我有一个DelegateCommand类,里面有两个构造函数。当我将我的属性传递给该类的构造函数时,我得到一条错误消息,上面写着:

代码语言:javascript
复制
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,这里是我所拥有的(没有注释以保持简短):

代码语言:javascript
复制
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);
            }
        }
    }
}

下面是我试图传递的属性和函数:

代码语言:javascript
复制
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()
        {

        }
    }
}

因为第一个错误必须处理一个重载的方法,所以我知道我忽略了一些非常简单的东西。至于第二个错误,既然我不能传递这个属性,那么有什么更好的方法来处理它呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-08 12:09:32

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

您应该使用应该发生的操作进行构造。例如,我想你的意思是调用"ExportList“:

代码语言:javascript
复制
_exportCommand = new DelegateCommand((o) => this.ExportList());

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15285646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档