Neandril
Neandril

Reputation: 119

Set a List<Object> to a Model using MVVM

I need some help with my C# Code, using MVVM pattern.

I have a class with a reference for a List of another class (for better understanding, I renamed my fields):

class Class1
{
    /* ... */
    public string myString { get; set; }
    public List<OtherClass> otherclass { get; set; }
}

The class here named "otherclass" looks like the following:

class OtherClass
{
    public OtherClass(string str1, string str2, string str3)
    {
        Str1 = str1;
        Str2 = str2;
        Str3 = str3;
    }

    public string Str1 { get; set; }
    public string Str2 { get; set; }
    public string Str3 { get; set; }
}

Finally, I have a ViewModel :

class MyViewModel :  INotifyPropertyChanged
{
    private readonly Class1 class1;

    /* ... */
    public string myString
    {
        get { return class1.MyString; }
        set
        {
            class1.MyString = value;
            OnPropertyChange("MyString");
        }
    }

    // Issue here
    // private List<OtherClass> _mylist = new List<OtherClass>;
    public List<OtherClass> OtherClass
    {
        get { return class1.OtherClass; }
        set
        {
            // class1.OtherClass.Add(value);
            class1.OtherClass = value;
            OnPropertyChange("OtherClass");
        }
    }

    /* ... */
}

When I need to fill my model, I just doing for example (in my code):

myViewModel.myString = myvalue;

Now, in my code I have a list with corrects values:

myList = new OtherClass(value1, value2, value3).

When I want to add this list of object in my model, my model stay null for that entry:

myViewModel.OtherClass = myList or myViewModel.OtherClass.Add(myList)

I'm surely make something wrong... If someone can help me please ?

Upvotes: 0

Views: 760

Answers (1)

elvira.genkel
elvira.genkel

Reputation: 1333

I do not see code where your list is initialized, please try to change in Class1:

public List<OtherClass> otherclass  { get; set; }= new List<OtherClass>();

or add default constructor to Class1 where List is initialized. While it is not initialized it is not possible to add items to the List

public Class1()
{
  this.otherclass = new List<OtherClass>();
}

Upvotes: 2

Related Questions