Wpf – Updating listbox without losing selected item, WPF

listboxwpf

Listbox is updated every sec and during work I need to select some of it's items and execute a command, which is impossible, because listbox is updated and loses it's selected item.

ObservableCollection is the ViewModel of my list.

I have some options in mind and perhaps there are better solutions:

  1. Detect new items in the list to be propagated and add new items to ObservableCollection without reinitializing ObservableCollection

  2. Detect changes in the old items and updated their fields if necessary.

This is somewhat cumbersome, though not difficult, but are there any other options?

Update, solution that I have

I've chosen the 3-d part: before an update has started, I save selected index of sorted collection and load a new collection and compare vs. old collection. I Know, this is not efficient, but for the current application this fits quite well: collections will never be more than some hundreds, ordinarily, no more 100. Each element of collection supports eager and lazy loading. And if there are changed items, they load their content from server, while other remain intact. And then I update observable collection, update changed items from server and set selected index in the viewmodel. Selecting an item manually solves the problem of losing focus after update.

Best Answer

Save the selected item's key before the list is updated. Find it in the new version of the list, and re-select it. Don't rely on the original reference, and allow for some other fellow removing it from the new list to select from.

Related Topic