I have an ObservableCollection _cableList
containing objects of type CableViewModel
. The CableViewModel
objects have a boolean property IsInDB
that should be set if another property Type
is listed i another collection. I listen to the PropertyChanged
event in order to update the IsInDB
property. This works as intended but I also need to update the IsInDB
property for items that are added to the collection. I attempt to solve this with the following code:
public MainViewModel()
{
_cableList = new ObservableCollection<CableViewModel>();
_cableList.CollectionChanged += _cableListChanged;
}
private void _cableListChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if(e.OldItems != null)
{
foreach (INotifyPropertyChanged item in e.OldItems)
item.PropertyChanged -= cablePropertyChanged;
}
if(e.NewItems != null)
{
foreach (INotifyPropertyChanged item in e.NewItems)
{
item.PropertyChanged += cablePropertyChanged;
// This causes an exception
MessageBox.Show("Collection changed - new Item");
var x = (CableViewModel)item;
x.IsInDB = IsInCableDB(x.Type);
}
}
}
The code causes an System.InvalidOperationException
that says something like "An ItemsControl
is inconsistent with its object source" or at least that´s my attempt to translate from the Swedish error message.
What is wrong with my code? Is there a another way to solve the task?
EDIT
I did not show the complete code in my original post as I didn't think it was related to the exception. But I was wrong.
In my original post I did not show or mention that I showed a MessageBox
for debugging purposes. It was shown each time a new object was added to the collection. The code above is now edited so that MessageBox.Show
line is included. After posting the original message here I removed the MessageBox
from the code and as a result the exception disappeared. Did the MessageBox
cause the UI to get out of sync with the collection? (The ObservableCollection
is bound to a DataGrid
)