Home > OS >  Add object to observable collection based on created class
Add object to observable collection based on created class

Time:03-09

I've created a class named Materials:

public class Materials : ObservableObject
{
    private List<String> _mat1List;
    public List<String> Mat1List
    {
        get { return _mat1List; }
        set { _mat1List = value; OnPropertyChanged(); }
    }

    private List<String> _mat2List;
    public List<String> Mat2List
    {
        get { return _mat2List; }
        set { _mat2List = value; OnPropertyChanged(); }
    }

    private List<String> _mat3List;
    public List<String> Mat3List
    {
        get { return _mat3List; }
        set { _mat3List = value; OnPropertyChanged(); }
    }

    private List<String> _mat4List;
    public List<String> Mat4List
    {
        get { return _mat4List; }
        set { _mat4List = value; OnPropertyChanged(); }
    }
}

Then I create 4 temporary lists to store info about them:

MaterialCollection = new ObservableCollection<Materials>();
ObservableCollection<String> tempMat1List = new ObservableCollection<String>();
ObservableCollection<String> tempMat2List = new ObservableCollection<String>();
ObservableCollection<String> tempMat3List = new ObservableCollection<String>();
ObservableCollection<String> tempMat4List = new ObservableCollection<String>();

After gathering all info about them, I cannot add them to my MaterialCollection:

MaterialCollection.Add( tempMat1List, tempMat2List, tempMat3List, tempMat4List );

Any tips please?

CodePudding user response:

You can implement a constructor for Materials which takes four lists and feed your _mat1List, _mat2List and so on.

Materials(List<string> materialList1, List<string> materialList2, List<string> materialList3, List<string> materialList4)
{
this._mat1List = materialList1;
this._mat2List = materialList2;
//...
}

And then you could do

MaterialCollection.Add(new Materials(tempMat1List, tempMat2List, tempMat3List, tempMat4List));

Please notice that as said in the comments, .Add method expects one parameter of the type of the collection you are adding it to.

  •  Tags:  
  • c#
  • Related