【发布时间】:2019-08-08 13:50:55
【问题描述】:
我正在尝试在 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。
【问题讨论】:
-
为什么要绑定 Text 属性?绑定 SelectedValue,并从字典中获取键的值。不绑定 SelectedValue 设置 SelectedValuePath 是没有意义的。
-
@Clemens - 感谢您的澄清。我已经更新了与 SelectedValueProperty 的绑定,现在它可以正常工作了。
标签: c# wpf combobox selectedvalue