我有一个 ComboBox,我已经创建了一个与项目列表的绑定,但是当我尝试绑定所选项目属性时,它什么也没做。当我只绑定 SelectedValueProperty 时,它曾经工作过。该类已经实现了 INotifyPropertyChanged。
public void ComboBoxBinding() {
Dictionary<long, string> myDictionary = new Dictionary<long, string>
Control control = new ComboBox();
comboBoxControl = (ComboBox)control;
comboBoxControl.SetBinding(ComboBox.ItemsSourceProperty, createFieldBinding("myDictionary"));
comboBoxControl.DisplayMemberPath = "Value";
comboBoxControl.SelectedValuePath = "Key";
binding = createFieldBinding(fieldProperty);
control.SetBinding(ComboBox.SelectedItemProperty, createFieldBinding("fieldProperty")); // <-- This doesn't seem to bind.
}
private Binding createFieldBinding(string propertyName) {
Binding binding = new Binding(fieldName);
binding.Source = this.DataContext;
binding.UpdateSourceTrigger = System.Windows.Data.UpdateSourceTrigger.PropertyChanged;
return binding;
}
我设置了一个可以更改字典变量的函数,并且 ComboBox 中的值会更改,但我无法更改 SelectedValueProperty。我怎么做?
编辑:如果我创建字典并手动设置 ItemsSource,它可以工作,但是当我设置绑定时,它不会。
Dictionary<long, string> myDictionary = new Dictionary<long, string>();
myDictionary.Add(1, "test1");
myDictionary.Add(2, "test2");
myDictionary.Add(3, "test3");
myDictionary.Add(4, "test4");
myDictionary.Add(5, "test5");
myDictionary.Add(6, "test6");
myDictionary.Add(7, "test7");
myDictionary.Add(8, "test8");
myDictionary.Add(9, "test9");
myDictionary.Add(10, "test10");
comboBoxControl.ItemsSource = myDictionary; //<-- This works, but if I use Binding instead of manually setting the ItemsSource, it does not work