WPF ComboBox resets selected item when item-source changes

Miroslav Bajtoš picture Miroslav Bajtoš · Feb 9, 2010 · Viewed 11.3k times · Source

Consider the following XAML:

<ComboBox Name="CompanyComboBox" 
    HorizontalAlignment="Stretch"
    ItemsSource="{Binding Path=GlobalData.Companies}" 
    SelectedValuePath="Id"
    SelectedValue="{Binding Customer.CompanyId, ValidatesOnDataErrors=True}"
    DisplayMemberPath="Name" />

GlobalData.Companies is a collection (IEnumerable<Company>) of companies; this collection can be reloaded on background (it is downloaded from a webservice). When this happens, ComboBox correctly reloads items via binding. However as a side-effect, it also resets the selected item!

I have used Reflector to inspect combo-box sources and apparently this is intended behavior.

Is there any "nice" way how to get around this? What I want to achieve, is that if the user selects "Company A" and reloads list of companies afterwards, then "Company A" stays selected (assuming it is in the new list).

Answer

BOBIN JOSEPH picture BOBIN JOSEPH · Apr 30, 2018

Please try with the following code. Enable the following property to the combo box

IsSynchronizedWithCurrentItem="True"