WPF Combobox SelectedItem hell

一笑奈何 提交于 2019-12-13 02:21:19

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/3447637/wpf-combobox-selecteditem-hell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!