繁体   English   中英

DelegateCommand的重载方法

[英]Overloaded method for 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()
        {

        }
    }
}

因为第一个错误必须处理重载方法,所以我知道我只是忽略了一些非常简单的东西。 至于第二个错误,由于我无法传递该Property,因此是一种更好的处理方法。

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

您应该使用应该采取的措施进行构建。 例如,我认为您的意思是调用“ ExportList”:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM