ReignOfComputer
ReignOfComputer

Reputation: 757

Adding to List replaces previous elements

I have a list that is used as a DataContext in a GridView.

This list is created with the following code:

        private void initializeStarredHub()
    {
        List<StarredData> starredList = new List<StarredData>();
        starredList.Add(new StarredData("ms-appx:///Images/Absence.png", "Sample Data 1"));
        starredList.Add(new StarredData("ms-appx:///Images/Absence.png", "Sample Data 2"));
        StarredHub.DataContext = starredList;
    }

Where StarredData is

    public class StarredData
    {
        public static string StarredImage { get; set; }
        public static string StarredTitle { get; set; }

        public StarredData() { }

        public StarredData(string itemImageSet, string itemNameSet)
        {
            StarredImage = itemImageSet;
            StarredTitle = itemNameSet;
        }
    }

The end result of the above is both starredList[0] and starredList[1] have "Sample Data 2" as the StarredTitle, meaning all previous values are overwritten by the latest set.

Why is this happening and how do I fix it?

Upvotes: 1

Views: 113

Answers (2)

Alex Costa
Alex Costa

Reputation: 306

You can fix it by removing the static keyword from your member definition.

Only one copy of a static member exists, regardless of how many instances of the class are created.

Check here: http://msdn.microsoft.com/en-us/library/79b3xss3.aspx

Upvotes: 1

King King
King King

Reputation: 63317

That's because you declared static members in StarredData class, just remove the static keywords:

public class StarredData
{
    public string StarredImage { get; set; }
    public string StarredTitle { get; set; }

    public StarredData() { }

    public StarredData(string itemImageSet, string itemNameSet)
    {
        StarredImage = itemImageSet;
        StarredTitle = itemNameSet;
    }
}

Upvotes: 2

Related Questions