-2

i got a quick question about binding the DisplayMember of my ComboBox. I have a list with a KeyValuePair for example:

1, Value1;
2, Value2;
3, Value3;

My SelectedValuePath is set to Key which is in my example "1". Now i want my DisplayMemberPath to show "Key - Value" so for example the Textbox should show "1 - Value1". Is that possible? Thank's in advance!

3 Answers3

1

You can do for instance so:

<ComboBox x:Name="cmb1" ItemsSource="{Binding YourDictionary}" SelectedValuePath="Key">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Key}"/>
                <TextBlock Text="-"/>
                <TextBlock Text="{Binding Value}"/>
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<TextBox Text="{Binding SelectedValue, ElementName=cmb1}"/>
Rekshino
  • 6,954
  • 2
  • 19
  • 44
1

If your ComboBox is not editable, you can create a DataTemplate for your key-value pairs.

<ComboBox ...>
   <ComboBox.ItemTemplate>
      <DataTemplate>
         <TextBlock>
            <Run Text="{Binding Key, Mode=OneWay}"/>
            <Run Text=" - "/>
            <Run Text="{Binding Value, Mode=OneWay}"/>
         </TextBlock>
      </DataTemplate>
   </ComboBox.ItemTemplate>
</ComboBox>
thatguy
  • 21,059
  • 6
  • 30
  • 40
1

One more way you can go is to use value converter:

<ComboBox x:Name="cmb1" ItemsSource="{Binding YourDictionary}" SelectedValuePath="Key">
    <ComboBox.ItemTemplate>
        <DataTemplate>
          <TextBlock Text="{Binding Converter={StaticResource YourConverter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>
<TextBox Text="{Binding SelectedValue, ElementName=cmb1}"/>

public class KeyValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is KeyValuePair<int, object> obj)//use your types here
        {
            return obj.Key.ToString() + "-" + obj.Value.ToString();
        }
        return value;
    }

    public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException("One way converter.");
    }
}
Rekshino
  • 6,954
  • 2
  • 19
  • 44