Disable adding item to collection

I am sure that there is an “easy” answer to this question, but at the moment it is eluding me.

In an MVVM application, I have an ObservableCollection property that is used to display some set of elements in a view.

private readonly ObservableCollection<MyType> mMyCollection = 
    new ObservableCollection<MyType>();
public ObservableCollection<MyType> MyCollection
{
    get { return mMyCollection; }
}

I want to restrict the users of this collection to simply use the property to add to the collection (i.e. I want to prevent this from being presented):

   viewModel.MyCollection.Add(newThing);   // want to prevent this!

Instead, I want to force the method to add elements, because there may be another thread using this collection, and I do not want to modify the collection while this thread processes it.

public void AddToMyCollection(MyType newItem)
{
    // Do some thread/task stuff here
}
+3
source share
2

ReadOnlyCollection , , , , , . . .

+5

, , , - , ObservableCollection<MyType> Add() ( ).

AddToMyCollection(MyType newItem) :

public new void Add(MyType newItem)
{
    // Do some thread/task stuff here
    // And call base.Add() if you need
}

, .

, - ( Add() ), ReadOnlyCollection, - .

+1

Source: https://habr.com/ru/post/1749217/


All Articles