禁用将项目添加到集合
我确信对此有一个“简单”的答案,但目前我还想不起来。
在 MVVM 应用程序中,我有一个 ObservableCollection 属性,用于在视图上显示某些元素集。
private readonly ObservableCollection<MyType> mMyCollection =
new ObservableCollection<MyType>();
public ObservableCollection<MyType> MyCollection
{
get { return mMyCollection; }
}
我想限制该集合的使用者简单地使用该属性添加到集合中(即我想从视图中防止这种情况):
viewModel.MyCollection.Add(newThing); // want to prevent this!
相反,我想强制使用一种方法来添加项目,因为可能有另一个方法线程使用该集合,并且我不想在该线程处理该集合时修改该集合。
public void AddToMyCollection(MyType newItem)
{
// Do some thread/task stuff here
}
I'm sure there's an "easy" answer to this, but for the moment it escapes me.
In an MVVM application, I have a property that is a ObservableCollection, used for displaying some set of elements on the view.
private readonly ObservableCollection<MyType> mMyCollection =
new ObservableCollection<MyType>();
public ObservableCollection<MyType> MyCollection
{
get { return mMyCollection; }
}
I want to restrict consumers of this collection from simply using the property to add to the collection (i.e. I want to prevent this from the view):
viewModel.MyCollection.Add(newThing); // want to prevent this!
Instead, I want to force the use of a method to add items, because there may be another thread using that collection, and I don't want to modify the collection while that thread is processing it.
public void AddToMyCollection(MyType newItem)
{
// Do some thread/task stuff here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在将集合提供给客户端之前,将其包装在
ReadOnlyCollection
中,因为您仍然拥有对它的非只读引用,您可以更改它,他们会看到更改,但无法更改它。请参阅此处查看示例。Wrap your collection in a
ReadOnlyCollection
before giving it to the client, since you still have your non-readonly reference to it you can change it and they'll see the changes but they can't change it. See here for a sample.虽然这需要一些工作,但我认为实现目标的唯一方法是创建一个新类,继承
ObservableCollection
并隐藏Add()
方法(通过 new 关键字)。您甚至可以将
AddToMyCollection(MyType newItem)
实现为:这样,自定义方法的使用是透明的。
如果您不希望任何人能够添加项目(通过 Add() 或您的自定义方法),您可以简单地返回一个 ReadOnlyCollection,它不允许任何人添加任何内容。
While it would require some work, the only way I can think to accomplish your goal is to create a new class, inherit from
ObservableCollection<MyType>
and hide theAdd()
method (via the new keyword).You could even implement
AddToMyCollection(MyType newItem)
as:That way, the usage of your custom method is transparent.
If you didn't want anybody to be able to add items (through Add() or your custom method), you could simply return a ReadOnlyCollection which wouldn't allow anybody to add anything.