Read only observable collection
I have m开发者_Go百科y class that has an internal observable collection. I want to pass the data in this to a user of the class via a function.
I don't want them to be able to change the objects inside of the observable collection or the collection itself.
What is the best way to do this performance and ease of use wise?
Probably using this: ReadOnlyObservableCollection<T>
. Note that you will have to write your own read-only wrappers for your objects, since the ReadOnlyObservableCollection<T>
only prevents updates to the collection itself.
I don't like using ReadOnlyObservableCollection<T>
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<T> : ICollection<T>, INotifyCollectionChanged
{
}
public interface IReadOnlyNotifyCollection<out T> : IReadOnlyCollection<T>, INotifyCollectionChanged
{
}
public class NotifyCollection<T> : ObservableCollection<T>, INotifyCollection<T>, IReadOnlyNotifyCollection<T>
{
}
public class Program
{
private static void Main(string[] args)
{
var full = new NotifyCollection<string>();
var readOnlyAccess = (IReadOnlyCollection<string>) full;
var readOnlyNotifyOfChange1 = (IReadOnlyNotifyCollection<string>) full;
//Covarience
var readOnlyListWithChanges = new List<IReadOnlyNotifyCollection<object>>()
{
new NotifyCollection<object>(),
new NotifyCollection<string>(),
};
}
}
What I did for this type of Implementation was to have a shared class with an underlying BindingList, for the entire client side to use. There was a public readonly getter, and in the actual UI presenter I included a type of Filtered List (Bound to the underlying singleton on instantiation) that would allow the client view to apply an Expression filter (LINQ Enabled too, based on underlying T) and, with the UI controls databound to this filtered list, list changes would automatically support UI Update only if it passed filter. And it was readonly, because the server side was publishing updates to an overall WCF controller class that passed them down to the List layer, skipping the UI entirely.
精彩评论