I am using WPF and C#
I have a button that opens a window, which also includes a button that adds an User object item to a listbox and I want the listbox index to be updated after insertion. I understood that the solution is about using observable class of INotifyCollectionChanged but actually I dont know how and where to use them. Can you help me on determining what and where to implement, register, fire etc.
Edit:
I succeeded this by Quartermeister’s help where my User object is collected in a list, but now I want to do the same thing where my object is collected in a dictionary
The easiest way is to use
System.Collections.ObjectModel.ObservableCollection<T>as your list. This implementsINotifyCollectionChangedandINotifyPropertyChangedfor you.You would have a property on your DataContext object of this type, and use data binding on ListBox.ItemsSource to bind it to that property. The ListBox will automatically update its list of elements when the collection changes.
In the class that is your DataContext:
In Xaml:
It sounds like you also want an observable dictionary, but unfortunately there is not one built into the framework. You could try using Dr. Wpf’s implementation of ObservableDictionary from his post “Can I bind my ItemsControl to a dictionary?”.