How to Preserve ListView Selected Item When Refreshing Data Source

I’m working with a ListView that connects to an ObservableCollection. Every time I need to refresh the data, I clear everything from the collection and add new items back. This approach works fine but I have one annoying problem - the selected item gets lost every time I do this refresh.

I tried to fix this by setting up two-way binding for the selected value like this:

SelectedValue="{Binding Path=CurrentSelection, Mode=TwoWay}"

Then in my code I do something like:

string savedSelection = this.CurrentSelection;
myCollection.Clear();
// populate with new data
this.CurrentSelection = savedSelection;

I thought the two-way binding would automatically update the ListView when I set the backend property again, but it doesn’t seem to work. The selection stays empty after the refresh. What am I missing here?

This happens because you’re saving the selected value as a string, but after refreshing the collection, the ListView can’t match that string to an actual object anymore. When you do CurrentSelection = savedSelection, you’re just assigning a string - but the ListView needs the actual item object from the refreshed collection. Don’t save just the string value. Save a unique identifier instead. If your items have an ID property, save that ID before clearing. After repopulating, loop through the new collection to find the item with the matching ID, then set that whole object as your CurrentSelection. Or try using SelectedItem binding instead of SelectedValue if you can work with object references directly. It’s usually more reliable for dynamic collections.

Interesting issue! Have you tried using CollectionChanged events to keep your selection? Instead of clearing everything, try updating items in place. Also - is CurrentSelection actually firing PropertyChanged notifications when you set it back? Debug that binding to see what’s really happening.

Yeah, classic mistake. The timing’s your problem - clear() breaks the binding instantly, so setting CurrentSelection after won’t work. Save the selected index instead of the value. After you repopulate, just set SelectedIndex back to that saved position. Way more reliable than matching objects or strings.