1

我在 WPF 中有一个非常有趣的问题

我通过代码创建一个组合框,并将其添加到控件中。

当我设置 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;  
}  

关于如何解决这个问题的任何想法?

4

2 回答 2

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;
    }
于 2010-08-10T12:08:19.800 回答
0

你在 GUI 中的那些 ComboBox 项目上有绑定吗?那么简单的原因是:在后面的代码中手动设置一个值会破坏绑定。

解决方法:在手动设置值之前,您可以使用BindingOperations静态函数获取绑定。

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

// do your changes here

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

于 2010-08-10T12:09:08.937 回答