WPF Combobox CompositeCollection bind ComboboxItem Content and list of strings

1.5k Views Asked by At

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"?

2

There are 2 best solutions below

0
user975561 On BEST ANSWER

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.

1
GazTheDestroyer On

The problem is because you are adding a ComboBoxItem to your collection, so your collection now has a bunch of strings and a ComboBoxItem. The Person.LastName binding wants a string, so WPF is calling ToString() on the ComboBoxItem, which happens to output "ComboBoxItem: " + its content.

You need to add another string rather than a ComboBoxItem. This is slightly tricky since normally you use resources for binding to properties, rather than literal xaml elements. However, you can do it by using ObjectDataProvider.

<CompositeCollection>
  <ObjectDataProvider ObjectInstance="{Static res:Labels.DummyName_Combobox_Selection}" />
  <CollectionContainer Collection="{Binding Source={StaticResource NamesSource}}" />
</CompositeCollection>