ObservableCollection - 无效参数

ObservableCollection - invalid arguments

我有一个 class,它是 C# WPF 应用程序中 ViewModel 层的一部分。创建新的 ObservableCollection 对象并将其分配给 this.AllPositions 时发生错误。该错误指出 ObservableCollection 有一些无效参数。 ObservableCollection 的工具提示表明它具有三个重载的构造函数。第一个不接收任何参数。第二个接收一个 IEnumberable<Dictionary<string,string>> collection 参数。第三个接收 List<Dictionary<string,string>> list 参数。我尝试了 _pRepo.GetPositions().AsEnumerable 和 _pRepo.GetPositions().ToList 的多种变体,但似乎无法让编译器满意。

如有任何帮助,我们将不胜感激。谢谢!

编辑: _pRepo.GetPositions() returns Systems.Collections.Generic.Dictionary<string, string>,准确的错误是 参数 1:无法从 'System.Collections.Generic.Dictionary' 转换为 'System.Collections.Generic.IEnumerable>'

public class MalfunctionInputVM : ViewModelBase {

        readonly PositionRepository _pRepo;

        public ObservableCollection<Dictionary<string, string>> AllPositions {
            get;
            private set;
        }

        public MalfunctionInputVM(PositionRepository pRepo) {

            if (pRepo == null)
                throw new ArgumentNullException("pRepo");

            _pRepo = pRepo;

            // Invalid arguments error occurs here...
            this.AllPositions = new ObservableCollection<Dictionary<string, string>>(_pRepo.GetPositions());
        }
    }

与错误消息完全一样:

ObservableCollection<Dictionary<string, string>>(argument);

argument 需要以下类型之一的参数:

IEnumerable<Dictionary<string,string>>
List<Dictionary<string,string>>

你在构造函数中传给它的是

的return值
_pRepo.GetPositions();

类型

Dictionary<string, string>

不能将元素当作集合来分配。

如果您希望字典本身是可观察的,那么 google 可以使用某些 ObservableDictionary 实现。或者,如果您确实需要一个包含多个词典的列表,并且打算让 _pRepo.GetPositions() 的 return 值成为该可观察集合中的第一项,您可以这样做:

this.AllPositions = new ObservableCollection<Dictionary<string, string>(
    new [] {_pRepo.GetPositions() });

根据您在评论中发布的错误,您的方法 _pRepo.GetPositions() returns 属于 Dictionary<string, string> 类型。现在你的 collection AllPositionsObservableCollection<Dictionary<string, string>> 的一种类型,这意味着它本质上是 Dictionary<string,string>.

List

您要做的是将 Dictionary 转换为列表。我的猜测是将 collection 类型从

更改为

ObservableCollection<Dictionary<string, string>>

ObservableCollection<KeyValuePair<string, string>>

这是因为您从您的方法中收到了一个字典。

你说你的GetPositions方法returnsDictionary<string, string>。但是您需要 IEnumerable<Dictionary<string, string>>,即 list 字典。

所以做一个数组:

new[] { _pRepo.GetPositions() }

在上下文中:

AllPositions = new ObservableCollection<Dictionary<string, string>>(
    new[] { _pRepo.GetPositions() });