Search code examples
c#wpfxamlcomboboxcompositecollection

WPF Combobox CompositeCollection bind ComboboxItem Content and list of strings


I am using WPF and I have a combobox in my view. My requirement is to display a list of names (ranging from 0 to n elements) and a localizable string "Dummy Name" in the combobox. So I take the ItemsSource of the combobox from two different sources, a list of strings called "names" + a localized string "Dummy Name". This all works well. All elements are displayed as they should. Here is my definition in WPF:

<CollectionViewSource Key="NamesSource" Source="{Binding Context.Data.Names}" />

<ComboBox HorizontalAlignment="Stretch" VerticalAlignment="Top" SelectedItem="{Binding Person.LastName}">
  <ComboBox.ItemsSource>
    <CompositeCollection>
      <ComboBoxItem Content="{Static res:Labels.DummyName_Combobox_Selection}"/>
      <CollectionContainer Collection="{Binding Source={StaticResource NamesSource}}" />
    </CompositeCollection>
  </ComboBox.ItemsSource>
</ComboBox>

The CollectionViewSource is part of a resource dictionary, I just left it out. The problem is with the ComboBoxItem element.

When it is selected in the combobox, it assigns the string "Combobox: Dummy Name" to Person.LastName, instead of "Dummy Name".

Setting SelectedMemberPath attribute to "Content" for the Combobox does not work either (I guess because the strings from Names do not have a Content property).

How can I make it assign "Dummy Name" to Person.LastName when "Dummy Name" is selected in the combobox, instead of "Combobox: Dummy Name"?


Solution

  • I now added a StaticExtension to the CompositeCollection instead of a ComboboxItem. So it looks like this now.

    <CollectionViewSource Key="NamesSource" Source="{x:Binding Context.Data.Names}" />
    
    <ComboBox HorizontalAlignment="Stretch" VerticalAlignment="Top" SelectedItem="{x:Binding Person.LastName}">
      <ComboBox.ItemsSource>
        <CompositeCollection>
          <x:Static Member="res:Labels.DummyName_Combobox_Selection"/>
          <CollectionContainer Collection="{x:Binding Source={StaticResource NamesSource}}" />
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>
    

    This seems to have the desired effect.