How can I make a read-only ObservableCollection property?

前端 未结 5 1619
你的背包
你的背包 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:25

    I don't like using ReadOnlyObservableCollection as it seems like a mistake / broken class; I prefer a contract based approach instead.

    Here is what I use that allows for covarience:

    public interface INotifyCollection 
           : ICollection, 
             INotifyCollectionChanged
    {}
    
    public interface IReadOnlyNotifyCollection 
           : IReadOnlyCollection, 
             INotifyCollectionChanged
    {}
    
    public class NotifyCollection 
           : ObservableCollection, 
             INotifyCollection, 
             IReadOnlyNotifyCollection
    {}
    
    public class Program
    {
        private static void Main(string[] args)
        {
            var full = new NotifyCollection();
            var readOnlyAccess = (IReadOnlyCollection) full;
            var readOnlyNotifyOfChange = (IReadOnlyNotifyCollection) full;
    
    
            //Covarience
            var readOnlyListWithChanges = 
                new List>()
                    {
                        new NotifyCollection(),
                        new NotifyCollection(),
                    };
        }
    }
    
        

    提交回复
    热议问题