问题描述
我想公开在包含对象的列表(从数据库)视图模型的属性。
I'd like to expose a property on a view model that contains a list of objects (from database).
我需要为只读此集合。也就是说,我想prevent添加/删除等,但允许在foreach和索引工作。我的目的是定义一个私有字段拿着编辑收集和只读公共属性引用它。如下:
I need this collection to be read-only. That is, I want to prevent Add/Remove, etc. But allow the foreach and indexers to work. My intent is to declare a private field holding the editable collection and reference it with a read-only Public Property. As follows
public ObservableCollection<foo> CollectionOfFoo {
get {
return _CollectionOfFoo;
}
}
不过,这种语法只是prevents改变引用集合。它并不prevent添加/删除等。
However, that syntax just prevents changing the reference to the collection. It doesn't prevent add/remove, etc.
什么是正确的方式做到这一点?
What is the right way to accomplish this?
推荐答案
在 [previously] 的接受的答案实际上将返回一个不同的 ReadOnlyObservableCollection每次ReadOnlyFoo是访问。这是浪费的,并可能导致微妙的错误。
The [previously] accepted answer will actually return a different ReadOnlyObservableCollection every time ReadOnlyFoo is accessed. This is wasteful and can lead to subtle bugs.
一个preferable的解决方案是:
A preferable solution is:
public class Source
{
Source()
{
m_collection = new ObservableCollection<int>();
m_collectionReadOnly = new ReadOnlyObservableCollection<int>(m_collection);
}
public ReadOnlyObservableCollection<int> Items
{
get { return m_collectionReadOnly; }
}
readonly ObservableCollection<int> m_collection;
readonly ReadOnlyObservableCollection<int> m_collectionReadOnly;
}
请参阅<一href="http://$c$c.logos.com/blog/2009/03/readonlyobservablecollection_anti-pattern.html">ReadOnlyObservableCollection反模式获取充分的讨论。
See ReadOnlyObservableCollection anti-pattern for a full discussion.
这篇关于我怎样才能使一个只读的ObservableCollection的财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!