How can I make a read-only ObservableCollection property?

前端 未结 5 1616
你的背包
你的背包 2021-01-03 17:55

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

5条回答
  •  离开以前
    2021-01-03 18:22

    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.

提交回复
热议问题