简体   繁体   中英

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM