2
votes

How can I maintain selection on a combobox if the currently selected item is replaced in the ItemsSource collection? In this case the collection is an ObservableCollection and of course if the currently selected item is replaced the combobox loses its selection - nothing is selected.

The ComboBox looks like:

                        <ComboBox 
                            Name="combobox"
                            SelectedValuePath="Id" 
                            DisplayMemberPath="Description" 
                            SelectedValue="{Binding Source={StaticResource cvs}, Path=Id, Mode=TwoWay}"/>

I cannot simply set the selected item on the combobox manually each time as the collection is manipulated in another generic class I cannot touch!

Thanks!

2
What is your criteria for keeping the selection? The index?Daniel Hilgarth
the item is only replaced not removed - i dont want the selection to changeLara
When you replace one item, then the old item IS removed and the new one is added. So, the previously selected item is not present in the collection any more. At its position, there is a new item. Do you want that new item to be selected? If so, please show us the code where you replace the item.Daniel Hilgarth
@Daniel yes that is what is happening, yes I do want the new item selected, the code is not special it is like: myCollection.Remove(oldItem); myCollection.Add(newItem);Lara

2 Answers

1
votes

you bind the selectedVaule to your Id Property. so if you want the new added Item to be the selected one, just set your Id property to the new Item and call OnPropertyChanged("Id")

myCollection.Remove(oldItem);
myCollection.Add(newItem);
Id = newItem;
OnPropertyChanged("Id")
0
votes

Use this code to select the new item:

combobox.SelectedItem = newItem;

UPDATE:
If the combobox is unknown to the part of the code that replaces the item, you need to do something like the following:

  • Subscribe to the CollectionChanged event of your collection.
  • When the event is fired and it says that a new item was added, execute the code as shown above.