How to make wpf combo box pull a special property

Viewed 143

I want to use a combo box for entering a plain integer value.

In my application, some numerical values have special meanings, but any numerical value must be able to be entered (typed in).

The combo box must therefore show an edit field with a drop-down arrow to the right.

If the drop-down arrow is clicked, the drop-down must present a list of explanations (strings) for those special numerical values that have special meanings (for example "103 - Wait for next turn").

If the user clicks an entry from the drop-down list (instead of typing in the corresponding value directly), the corresponding numerical value must be transferred to the edit field.

I have tried the following:

  • I set the ComboBox's IsEditable property to true
  • I bind the ItemsSource property to a collection of objects which have both a numerical property (named "Value") and a string property (named "Explanation").
  • I set the DisplayMemberPath property to "Explanation" (the name of the string property above)

With that in place, I can freely type in any number I like, and the string explanation of each special number is properly displayed in the drop-down list. This is exactly what I want.

However, when I select one of the explanations from the drop-down list, it's the explanation string that gets transferred to the edit field, not the corresponding numerical value.

Question: How can I make the combo box transfer the numerical property ("Value") instead of the explanation text when I click an item from the drop-down list?

1 Answers

Use a data template for showing the explanation text in the drowp-down.

For showing the value in the text edit field, set the attached property TextSearch.TextPath for the ComboBox to the name of the value property in your "special values" type.

If the ComboBox should not auto-complete possible special values when entering a number, set its IsTextSearchEnabled property to false. (Note that this would also disable automatic selection of a special value in the drop-down if you happen to enter one in the edit field.)

The definition of the ComboBox should thus look similar to this:

<ComboBox ItemsSource="{Binding ...}"
          IsEditable="True"
          TextSearch.TextPath="Value"
          IsTextSearchEnabled="False">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Explanation}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
Related