0

I have a combobox and I have bound it to a dictionary.

The dictionary is defined as:

        Cities = new Dictionary<string, string>
        {
            {"USA", "NewYork"},
            {"UK", "London"},
            {"Canada", "Toronto"}
        };

The combobox is bound to the dictionary as follows:

                    <ComboBox x:Name="CitiesComboBox" Grid.Column="1" ItemsSource="{Binding Cities}" SelectedItem="{Binding SelectedCity}" Margin="10" Background="Transparent">
                        <ComboBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Text="{Binding Key}" FontSize="15" VerticalAlignment="Center"/>
                                    <TextBlock Text="{Binding Value, Mode=OneWay, StringFormat='{}  {0}'}" VerticalAlignment="Center"/>
                                </StackPanel>
                            </DataTemplate>
                        </ComboBox.ItemTemplate>
                    </ComboBox>

The binding works fine but I am having trouble setting the selecteditem of the combobox to "London".

Since the itemtemplate is not a single string property, the combobox selecteditem property is not binding to string value "London"

Thanks, Sath

Sath
  • 1
  • 1

1 Answers1

0

You can set the SelectedValuePath property to "Value". Then when you set SelectedValue to "London", ComboBox will map its selection to the item that has "London" set to its Value property, which will solve your problem Here is a post that goes in deeper details on the different usage of the selection properties.

zaphod-ii
  • 424
  • 3
  • 11