WPF Combobox SelectedItem hell [英] WPF Combobox SelectedItem hell
问题描述
我在WPF中有一个非常有趣的问题
Im having a very funny issue in WPF
我通过代码创建一个Combobox,并将它添加到控件。
Im creating a Combobox through code, and adding it to a control.
当我设置Combobox.SelectedItem或Combobox.SelectedIndex或Combobox.SelectedValue时,我无法从Combox项目中选择其他选项。
When I set the Combobox.SelectedItem or Combobox.SelectedIndex or Combobox.SelectedValue I am unable to select another option from the Combox items.
ForeignKeyDisplayAttribute attribute = (ForeignKeyDisplayAttribute)this.GetAttribute(typeof(ForeignKeyDisplayAttribute), property);
if (attribute != null)
{
ForeignKeyDisplayAttribute fkd = attribute;
Type subItemType = fkd.ForeignKeyObject;
contentControl = new ComboBox();
object blankItem = System.Activator.CreateInstance(subItemType, new object[] { });
System.Reflection.MethodInfo method = subItemType.GetMethod("Load", new Type[] { typeof(int) });
object innerValue = method.Invoke(null, new object[] { value });
System.Collections.IList selectedSubItems = (System.Collections.IList)subItemType.GetMethod("Load", Type.EmptyTypes).Invoke(null, new object[] { });
selectedSubItems.Insert(0, blankItem);
((ComboBox)contentControl).SelectedValuePath = fkd.IdField;
((ComboBox)contentControl).DisplayMemberPath = fkd.DescriptionField;
((ComboBox)contentControl).ItemsSource = selectedSubItems;
((ComboBox)contentControl).InvalidateVisual();
// If I use any of the two below lines or SelectedItem then I can't change the value via the UI.
((ComboBox)contentControl).SelectedIndex = this.FindIndex(selectedSubItems, value);
((ComboBox)contentControl).SelectedValue = value;
}
有关如何解决这个问题的任何想法吗?
Any idea's as to how I can fix this?
推荐答案
在GUI中的ComboBox项目上有绑定吗?然后简单的原因是:在代码中手动设置值破坏绑定。
Do you have Bindings on those ComboBox items in GUI? Then the simple reason is: setting a value manually in the code behind destroys the binding.
Workarround:
手动设置值之前,您可以获得绑定 静态函数。
Workarround: Before setting the value manually you can get the binding with the BindingOperations static functions.
Binding b = BindingOperations.GetBinding(yourComboBox, ComboBox.SelectedItemProperty);
// do your changes here
BindingOperations.SetBinding(yourComboBox, ComboBox.SelectedItemProperty, b);
Jan
这篇关于WPF Combobox SelectedItem hell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!