1

I want to bind my combo box ItemsSourse to the "value" i.e. (string component) of the

ObservableCollection<KeyValuePair<object, string>>.

How can I do that?

aromore
  • 977
  • 2
  • 10
  • 25

2 Answers2

1

You could bind the ItemsSource to the ObservableCollection and then set the DisplayMemberPath to Value:

<ComboBox ItemsSource="{Binding YourCollection}" DisplayMemberPath="Value" />

The values in the combo box will then match the Values from the KeyValuePairs.

Johnbot
  • 2,169
  • 1
  • 24
  • 24
1

The easiest way to go would be to use the DisplayMemberPath property:

<ComboBox ItemsSource="{Binding Pairs}" DisplayMemberPath="Value" />

Alternatively, you could expose a new property in your viewmodel that will only contain the values. For example:

public ObservableCollection<string> AllValues { get; set; }

public ViewModel()
{
    AllValues = new ObservableCollection<string>(Pairs.Select(x => x.Value));
}
<ComboBox ItemsSource="{Binding AllValues}" />
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
  • Although the thought of using `ObservableCollection` for data binding is right, this is not a feasible solution: [the constructor that takes an `IEnumerable` as argument](https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1.-ctor?view=netframework-4.7.2#System_Collections_ObjectModel_ObservableCollection_1__ctor_System_Collections_Generic_IEnumerable__0__) _copies_ all values, effectively voiding the purpose of binding to the values of the original `KeyValuePair` collection. – Informagic Mar 15 '19 at 00:57