user857521
user857521

Reputation:

Changing ObservableCollection Value throws read only error

I have an ObservableCollection defined as

public ObservableCollection<KeyValuePair<string, double>> comboBoxSelections 
{ 
 get; 
 set; 
}

later on in my code I need to iterate the collection and change some values only but keep the same key. I've tried the following

        for (int i = 0; i < comboBoxSelections.Count ; i++)
        {
            comboBoxSelections[i].Value = SomeDoubleValue;
        }

but this gives error Property or indexer 'System.Collections.Generic.KeyValuePair<string,double>.Value' cannot be assigned to -- it is read only

Can someone please explain why I get the error and how to allow updates to the ObservableCollection?

Upvotes: 0

Views: 450

Answers (2)

herzmeister
herzmeister

Reputation: 11297

It's not the ObservableCollection<T> that is read-only, it's the KeyValuePair<TKey, TValue>, because the latter is a struct. It is a good design practice for structs to be immutable.

The correct way to update your collection is

comboBoxSelections[i] =
    new KeyValuePair<string, double>(comboBoxSelections[i].Key, someDoubleValue);

Upvotes: 2

Bartosz
Bartosz

Reputation: 3358

Well, the error message is clear. The Value property of KeyValuePair is read only. I cannot give detailed answer for second part of the question, but quick googling gives:

http://blogs.microsoft.co.il/blogs/shimmy/archive/2010/12/26/observabledictionary-lt-tkey-tvalue-gt-c.aspx

Upvotes: 1

Related Questions