Search code examples
wpfsortingxamlcomboboxcollectionviewsource

WPF Combobox sorting, but initally no entry selected?


I implemented sorting for a WPF combobox using the following XAML:

<CollectionViewSource x:Key="SortedAreas" Source="{Binding AllAreas}">
  <CollectionViewSource.SortDescriptions>
    <scm:SortDescription PropertyName="Name"/>
  </CollectionViewSource.SortDescriptions>
</CollectionViewSource>

<ComboBox Name="PhotoLocationAreaComboBox"
          ItemsSource="{Binding Source={StaticResource SortedAreas}}"                
          DisplayMemberPath="Name">
</ComboBox>

That works basically fine - the entries are sorted, but there is a side effect:

  • Before I added the sorting (binding directly to AllAreas which is an ObservableCollection, internally no combobox entry was selected (empty)
  • After the sorting, the first sorted entry is automatically pre-selected

Any idea how to restore the original behaviour (no entry selected) with the sorting? I tried SelectedIndex = "0", but that did not help.


Solution

  • Set the IsSynchronizedWithCurrentItem property to false:

    <ComboBox Name="PhotoLocationAreaComboBox"
              ItemsSource="{Binding Source={StaticResource SortedAreas}}"   
              DisplayMemberPath="Name"
              IsSynchronizedWithCurrentItem="False">
    </ComboBox>