Exception: ItemsControl is inconsistent with its items source

This can get tricky if you don’t realise where its arising from.

I had one listbox with its ItemsSource Binding set to List<T> in viewmodel. Via a command, i was updating the listbox items source. Now it was fine until I added a new item to the list and fired RaisePropertyChanged() somewhere in the middle of the code for Command execution.

What happens now is that UI is asked to refresh its state before Command execution is complete. i.e. UI finds its ItemSource collection different to one on the source(ViewModel property) because the Source property on ViewModel is now increased with one additional item but UI still is hanging around with one less item in list!

The best way to resolve this was to use ObservableCollection<> so there won’t be any need for change notification. However, in principle, this error can be avoided if UI is asked refresh only after the command execution(or whatever process is updating the source collection) is done. This requires use of dispatcher.

_dispatcherService.Dispatch(() => RaisePropertyChanged(nameof(Employees)))

I have injected _dispatcherService in my class so just calling it but in essence this will defer the UI refresh until its safe to do so i.e. after current processing is over

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s