Is it possible to return a read-only ObservableCollection that the caller can't modify?
Consider the following code:
public ObservableCollection<Message> Messages {
get { return new ObservableCollection<Message>(); }
}
Is there anything I can do to prevent the caller code from adding/removing/changing items?
EDIT: Sorry, everyone, I just noticed it's a dupe, but the accepted answer is开发者_运维知识库 wrong.
What about using ReadOnlyObservableCollection
Code would be:
public ReadOnlyObservableCollection<Message> Messages
{
get { return new ReadOnlyObservableCollection<Message>(new ObservableCollection<Message>()); }
}
Having read aboutReadOnlyObservableCollection Anti Pattern I realise the above is the not a good approach and may lead to subtle bugs. The suggested approach is:
public class MyClass
{
public MyClass()
{
myCollection = new ObservableCollection<Message>();
myReadOnlyCollection = new ReadOnlyObservableCollection<Message>(myCollection);
}
public ReadOnlyObservableCollection<Message> Messages
{
get { return myReadOnlycollection; }
}
private readonly ObservableCollection<Message> myCollection;
private readonly ReadOnlyObservableCollection<Message> myReadOnlyCollection;
}
Why do you need a read only ObservableCollection. If this collection is read only you don't need to observe it. Consider a Collection<T>
Return a ReadOnlyObservableCollection
instead:
private ReadOnlyObservableCollection<Message> _Messages;
public ReadOnlyObservableCollection<Message> Messages {
get { this._Messages = this._Messages ?? new ReadOnlyObservableCollection(new ObservableCollection<Message>()); return this._Messages; }
}
What about to use the ReadOnlyObservableCollection< T >
精彩评论