How can I make a read-only ObservableCollection property?

Posted by thrag on Stack Overflow See other posts from Stack Overflow or by thrag
Published on 2009-11-19T14:33:38Z Indexed on 2010/05/20 14:00 UTC
Read the original article Hit count: 169

Filed under:
|
|

I'd like to expose a property on a view model that contains a list of objects (from database).

I need this collection to be read-only. That is, I want to prevent Add/Remove, etc. But allow the foreach and indexers to work. My intent is to declare a private field holding the editable collection and reference it with a read-only Public Property. As follows

public ObservableCollection<foo> CollectionOfFoo { 
     get { 
         return _CollectionOfFoo;
     }
}

However, that syntax just prevents changing the reference to the collection. It doesn't prevent add/remove, etc.

What is the right way to accomplish this?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about c#