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 A
The [previously] accepted answer will actually return a different ReadOnlyObservableCollection every time ReadOnlyFoo is accessed. This is wasteful and can lead to subtle bugs.
A preferable solution is:
public class Source
{
Source()
{
m_collection = new ObservableCollection();
m_collectionReadOnly = new ReadOnlyObservableCollection(m_collection);
}
public ReadOnlyObservableCollection Items
{
get { return m_collectionReadOnly; }
}
readonly ObservableCollection m_collection;
readonly ReadOnlyObservableCollection m_collectionReadOnly;
}
See ReadOnlyObservableCollection anti-pattern for a full discussion.