【问题标题】:Issue with ComboBox SelectedValuePath in code behind后面代码中的 ComboBox SelectedValuePath 问题
【发布时间】: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


【解决方案1】:
frameWorkElement.SetBinding(ComboBox.SelectedValueProperty, binding);

如果ComboBoxDataContext 或父元素设置为具有名为“ComboBoxSourceValue”的string 源属性的类的实例,则应该可以工作。

SelectedValuePath 指的是SortedDictionaryKeyValuePair&lt;TKey, TValue&gt; 的属性。您仍然需要将该值绑定到您的源属性。

【讨论】:

  • 谢谢。我已按照您的建议更新了与 SelectedValueProperty 的绑定,现在可以正常工作了。
猜你喜欢
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 2011-07-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-10
相关资源
最近更新 更多