WPF Combobox SelectedItem hell

2019-07-31 13:48发布

Im having a very funny issue in WPF

Im creating a Combobox through code, and adding it to a control.

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?

2条回答
不美不萌又怎样
2楼-- · 2019-07-31 14:46

Well found the answer.

Turns out I had incorrectly coded the overridden object Equals method, and it was always returning false.

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

should have been

    public override bool Equals(object obj)
    {
        if (obj.GetType() == this.GetType() && obj is IId)
            return this.Id.Equals(((IId)obj).Id);
        return false;
    }
查看更多
爷、活的狠高调
3楼-- · 2019-07-31 14:46

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: 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

查看更多
登录 后发表回答