GertR
GertR

Reputation: 75

WPF How to set selected item different to items list (Combobox)?

I have a data grid view with a combobox column. Is is possible to have the value in the drop down list but after selecting one item to have the key of this item in the cell?

E.g. my key-value-pairs: 1 = Car, 2 = Plane, 3 = Submarine... The dropdown list should show Car, Plane, Submarine... and when "Plane" is selected only "2" is in the cell.

Some idesas?

Upvotes: 0

Views: 918

Answers (3)

GertR
GertR

Reputation: 75

Maybe I explaned me worng but after hours of struggeling I came to this solution:

           <ComboBoxColumn  DisplayMemberPath="Value" SelectedValueMemberPath="Key"  DataMemberBinding="{Binding myCollection, Mode=TwoWay}" >
                <common:FWGridViewComboBoxColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Key}" />
                    </DataTemplate>
                </common:FWGridViewComboBoxColumn.CellTemplate>
            </ComboBoxColumn>

This is exact what I was looking for. Thanks to S. Spindler, you gave me the right direction where I shold go.

Upvotes: 0

S. Spindler
S. Spindler

Reputation: 546

I think you can simply use an ItemTemplate to display the property you want to:

<ComboBox>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Value}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Alternatively:

<ComboBox DisplayMemberPath="Value" />

Upvotes: 1

Use the DisplayMemberPath property specify the name of the property you want to display as the text of the combobox items.

Use the SelectedValuePath property to specify the name of the property you want to use for the SelectedValue of the combobox.

<ComboBox
    DisplayMemberPath="Value"
    SelectedValuePath="Key"
    />

Thus if you have an item { Key = 2, Value = "Plane" }, the user will see "Plane" in the combobox item, and when he selects, the SelectedValue property of the ComboBox will return 2, while the SelectedItem property of the combobox will return the whole selected object { Key = 2, Value = "Plane" }.

ComboBox.ItemTemplate is appropriate if you want to display the combobox items in some special or elaborate way, but if all you want is just the string value of a property, DisplayMemberPath does the job simply and readably.

Upvotes: 0

Related Questions