Search code examples
c#wpfcomboboxselectedvalue

Issue with ComboBox SelectedValuePath in code behind


I am trying to bind a Dictionary to my ComboBox in a WPF application.

SortedDictionary<string, string> result = new SortedDictionary<string, string>();

((ComboBox)frameWorkElement).ItemsSource = result;
((ComboBox)frameWorkElement).DisplayMemberPath = "Value";
((ComboBox)frameWorkElement).SelectedValuePath = "Key";


((ComboBox)frameWorkElement).MinWidth = 200;
frameWorkElement.Name = "ListOfValues";
var binding = new Binding("ComboBoxSourceValue")
{
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

frameWorkElement.SetBinding(ComboBox.TextProperty, (BindingBase)binding);

In UI side, values are binding properly. But in the submit action, I am able to see only value (Display value) only selected value's Key.


Solution

  • frameWorkElement.SetBinding(ComboBox.SelectedValueProperty, binding);
    

    should work provided that the DataContext of the ComboBox, or a parent element, is set an instance of a class that has a string source property named "ComboBoxSourceValue".

    SelectedValuePath refers to a property of the KeyValuePair<TKey, TValue> in the SortedDictionary. You still need to bind the value to your source property.