Search code examples
c#.netpropertiesobservablecollectionencapsulation

Encapsulation of ObservableCollection does not work


My property is:

private static ObservableCollection<Wynik> lottoWyniki = new ObservableCollection<Wynik>();
    public static ObservableCollection<Wynik> LottoWyniki
    {
        get { return lottoWyniki; }
        set { lottoWyniki = value; }
    }

And when later in the code I want to add objects to this collection:

for(i=2;i<=7;i++)
                LottoWyniki.Add(new Wynik(i,Date));

Every new obcject that I'm adding is replacing all objects that were there before. So at the finish of this code I've got ObservableCollection that contains one (last) object repeated 6 times. What I'm I doing wrong?

EDIT: In constructor of Wynik I'm doing:

public Wynik (int l, DateTime d) 
{  
    Liczba = l;  
    Data = d; 
}

Class Wynik:

class Wynik
{
    private static DateTime data;
    public static DateTime Data
    {
        get { return data; }
        set { data = value; }
    }

    private static int liczba;
    public static int Liczba
    {
        get { return liczba; }
        set { liczba = value; }
    }

    public Wynik (int l, DateTime d)
    {
        Liczba = l;
        Data = d;
    }
}

Solution

  • Most likely your class's variables are static. Try changing all properties to non-static members and this will resolve your issue.