我试图在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
。
答案 0 :(得分:1)
frameWorkElement.SetBinding(ComboBox.SelectedValueProperty, binding);
只要DataContext
的{{1}}或父元素被设置为具有ComboBox
源属性名为“ ComboBoxSourceValue”的类的实例,就应该起作用。
string
指SelectedValuePath
中KeyValuePair<TKey, TValue>
的属性。您仍然需要将该值绑定到您的源属性。