后面代码中的ComboBox SelectedValuePath问题

时间:2019-08-08 13:50:55

标签: c# wpf combobox selectedvalue

我试图在WPF应用程序中将Dictionary绑定到我的ComboBox

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);

在UI端,值正确绑定。但是在提交操作中,我只能看到值(Display value)仅是选定值的Key

1 个答案:

答案 0 :(得分:1)

frameWorkElement.SetBinding(ComboBox.SelectedValueProperty, binding);

只要DataContext的{​​{1}}或父元素被设置为具有ComboBox源属性名为“ ComboBoxSourceValue”的类的实例,就应该起作用。

stringSelectedValuePathKeyValuePair<TKey, TValue>的属性。您仍然需要将该值绑定到您的源属性。