Search code examples
c#wpfentity-frameworkmvvm

Set ComboBox Selected Item/Text to Value path of ItemsSource


I have an Entity table which lists ISO Country Codes and their descriptions in order to populate a ComboBox. I then have another table which sets a 'Nationality' to the selected value of the ComboBox. I have no foreign-key constraints between the IsoCountryCodes and my other table.

I want to be able to set the SelectedItem of the ComboBox to the selected IsoCountryCode, but I want to save the SelectedValue to the 'Nationality' field.

I've tried setting the SelectedItem of the ComboBox to my 'Nationality' (string) field but it is just doing a ToString() on the IsoCountryCode. When I set the 'Text' field instead of SelectedItem, it is saving the DisplayPath value to the 'Nationality' field.

I was wondering if there was a way to get the ValuePath value to save to the field without any foreign key constraints, whilst still displaying a valid DisplayPath to the user?

Example of IsoCountryCode table:

IsoCode     IsoDescription

'GBR'      'United Kingdom'
'USA'      'United States of America'

Example of the other table:

PassengerId  PassengerName  PassengerNationality   PassengerDocumentIssuingCountry
1            'Carter, John'   'GBR'                'USA'

And my current Xaml:

<xctk:WatermarkComboBox x:Name="uxNationalityCmbo" Margin="0,0,5,5" Watermark="Nationality" 
      Grid.Row="2" ItemsSource="{Binding CountryCodeCollection}" SelectedValuePath="IsoCode" DisplayMemberPath="IsoDescription" 
      IsTextSearchEnabled="True" Text="{Binding SelectedPassenger.PassengerNationality, TargetNullValue=''}"/>

Changing the selected value now would to USA would change the entity PassengerNationality to 'United States of America', whereas I need 'USA'


Solution

  • You should bind the SelectedValue property to the PassengerNationality source property:

    <xctk:WatermarkComboBox x:Name="uxNationalityCmbo" Margin="0,0,5,5" Watermark="Nationality" 
      Grid.Row="2" ItemsSource="{Binding CountryCodeCollection}" SelectedValuePath="IsoCode" DisplayMemberPath="IsoDescription" 
      IsTextSearchEnabled="True" SelectedValue="{Binding SelectedPassenger.PassengerNationality, TargetNullValue=''}"/>