2010-08-10 107 views
1

林在WPF中有一个非常有趣的问题WPF Combobox SelectedItem地狱

我通过代码创建一个Combobox,并将其添加到控件。

当我设置Combobox.SelectedItem或Combobox.SelectedIndex或Combobox.SelectedValue时,我无法从Combox项目中选择其他选项。

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; 
} 

任何想法如何我可以解决这个问题?

+1

大量的代码(我们不能编译)。任何机会在一个最小但完整的程序中重现这一点? – 2010-08-10 10:25:18

+0

我看到我能做什么,它是一个更大程序的一部分。但我确定我可以抽出一个样本。 – 2010-08-10 10:37:58

回答

0

那么找到了答案。

原来,我错误地编写了重写的对象Equals方法,并且它总是返回false。

public override bool Equals(object obj) 
    { 
     if (obj is IId) 
      return this.Id.Equals(((IId)obj).Id); 
     return false; 
    } 

应该已经

public override bool Equals(object obj) 
    { 
     if (obj.GetType() == this.GetType() && obj is IId) 
      return this.Id.Equals(((IId)obj).Id); 
     return false; 
    } 
0

你有对GUI的组合框项绑定?那么简单的原因是:在代码中手动设置一个值破坏绑定。

Workarround: 在手动设置该值之前,您可以获得与静态函数绑定的绑定操作。

Binding b = BindingOperations.GetBinding(yourComboBox, ComboBox.SelectedItemProperty); 

// do your changes here 

BindingOperations.SetBinding(yourComboBox, ComboBox.SelectedItemProperty, b); 

+0

不,我正在做很长时间的绑定(无法获得数据绑定工作) – 2010-08-10 12:45:44