Wandy Wijayanto Wandy Wijayanto - 3 months ago 30
C# Question

Adding data to ObservableCollection in WPF

I have some problem here. Here it is:
I have this class

public class NewsFeedResources
{
public string Name { get; set; }
public string Id { get; set; }
public string Message { get; set; }

public static ObservableCollection<NewsFeedResources> _newsfeed = new ObservableCollection<NewsFeedResources>
{

new NewsFeedResources { Name = "Joe", Id = "1", Message="Foo" },
new NewsFeedResources { Name = "Wandy", Id = "2", Message="Bar" },
new NewsFeedResources { Name = "Yuliana", Id = "3", Message="Baz" },
new NewsFeedResources { Name = "Hardi", Id = "4", Message="Baz" },

};

public static ObservableCollection<NewsFeedResources> newsFeedResources
{ get { return _newsfeed; }

}
}


If I have another data such as

Name=John, Id=5, Message="Stack overflow"

Name=Jane, Id=6, Message="Hello world"

How can I add the data into the class, but not from the constructor? Thanks for the help

Answer

ObservableCollection exposes the Collection<T>.Add Method:

Adds an object to the end of the Collection.

So you'd have:

_newsfeed.Add(new NewsFeedResources {Name = "John",
                                     Id = 5,
                                     Message = "Stack overflow"});
_newsfeed.Add(new NewsFeedResources {Name = "Jane",
                                     Id = 6,
                                     Message = "Hello world"});

(typed from memory)