I’m having trouble with my ListView control in WPF. It’s linked to an observable collection that I often update. My update method clears the collection and adds new values. This works fine but it makes the ListView lose its selection.
I tried to fix this by using two-way binding for the SelectedValue:
var previousChoice = this.ChosenItem;
myCollection.Clear();
// Add new items
this.ChosenItem = previousChoice;
I thought the two-way binding would make changes to the backend property show up in the ListView, but it’s not working. Any ideas on how to keep the selection after updating the collection? Thanks for any help!
hmm, interesting problem! have u considered using a CollectionView instead? it can maintain selection even when the underlying collection changes. also, curious if u’ve tried updating items individually rather than clearing the whole collection? might help preserve selection. what’s ur specific use case for updating the collection?
hey mate, had similar issue. try using selectedItem instead of selectedValue in ur binding. also, make sure ur chosenItem property raises propertyChanged. if that don’t work, maybe try saving the index instead of the item itself. good luck!
I’ve encountered this issue before. One effective approach is to implement the INotifyPropertyChanged interface for your ChosenItem property. This ensures the UI is notified when the property changes. Additionally, consider using ObservableCollection methods like Remove and Add instead of Clear and re-adding all items. This can help maintain selection state. If you must clear the collection, try storing both the selected item and its index before updating, then restore both afterward. This combination of techniques has worked well in my projects.