Geeks With Blogs
Patrice Calve Life's short, have fun

Use a ReadOnlyObservableCollection when you allow people to subscribe to changes to a collection, without allowing them to make changes to the collection.

ReadOnlyObservableCollection is a object from System.Collections.ObjectModel.

  • ReadOnly: Because there's no Add/Remove method
  • Observable: When an item is added or removed, it will fire an event (INotifyCollectionChanged).

But, if it's ReadOnly, how can it be Observable?  Because the object is actually a wrapper to a "real" collection.  When you create a new instance of this object, in the constructor, you need to specify a "real" collection.

So, you actually need two objects:

  1. A private, modifyable, observable collection
  2. A public, ReadOnlyObservableCollection

Here's a simple console app example to illustrate the use.  Persons is public but ReadOnly, whereas _myPeople is private, unexposed, but modifiable.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.ObjectModel; namespace ConsoleApplicationForTestingCollections { class Program { static void Main(string[] args) { var ds = new DataService(); ds.Init(); // Note 1: here that we're using a "readonly" collection... Console.WriteLine(ds.Persons[0].FullName); Console.Read(); } } public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } } } public class DataService { public ReadOnlyObservableCollection<Person> Persons { get; private set; } private ObservableCollection<Person> _myPeople; public DataService() { _myPeople = new ObservableCollection<Person>(); this.Persons = new ReadOnlyObservableCollection<Person>(_myPeople); } public void Init() { // Note 2: here, we're adding an item in a private, unexposed, collection _myPeople.Add(new Person() { FirstName = "Foo", LastName = "Bar" }); } } }
Posted on Sunday, May 19, 2013 6:38 PM | Back to top


Comments on this post: ReadOnlyObservableCollection

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Patrice Calvé | Powered by: GeeksWithBlogs.net