Search code examples
c#wpfmvvm

ObservableCollection - invalid arguments


I have a class that is part of a ViewModel layer in a C# WPF application. An error is occurring when creating a new ObservableCollection object and assigning it to this.AllPositions. The error states that the ObservableCollection has some invalid arguments. The tooltip for ObservableCollection indicates that it has three overloaded constructors.

First one receives no parameters. Second one receives an IEnumerable<Dictionary<string,string>> collection parameter. Third one receives List<Dictionary<string,string>> list parameter. I've tried numerous variations of _pRepo.GetPositions().AsEnumerable and _pRepo.GetPositions().ToList but can't seem to make the compiler happy.

Any help would be greatly appreciated. Thanks!

Edit:

_pRepo.GetPositions() returns Systems.Collections.Generic.Dictionary<string, string>, and the exact error is

Argument 1: cannot convert from 'System.Collections.Generic.Dictionary<string,string>' to 'System.Collections.Generic.IEnumerable<System.Collections.Generic.Dictionary<string,string>>'

Code:

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());
        }
}

Solution

  • Exactly like the error message states:

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

    Expects an argument of one of the following types for argument:

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

    What you pass it in the constructor is the return value of

    _pRepo.GetPositions();
    

    Which is of type

    Dictionary<string, string>
    

    You cannot assign an element as if it was a collection.

    If you intended for the dictionary itself to be observable, some ObservableDictionary implementations are available if you google for them. If alternatively you do need a list containing multiple dictionaries, and intended for the return value of _pRepo.GetPositions() to be the first item in that observable collection, you can do:

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