简体   繁体   中英

SelectionChanged Event of WPF comboBox is not firing if it has same items in it

if im using following type of code then SelectionChanged Event of WPF comboBox is not firing

cmbFunctionsList.Items.Add("sameItem");
cmbFunctionsList.Items.Add("sameItem");
cmbFunctionsList.Items.Add("sameItem");
cmbFunctionsList.Items.Add("sameItem");
cmbFunctionsList.Items.Add("sameItem");

Is there any work around of this.

WPF Combo Boxes will not change the selected item if the currently selected item and the new one that selected are considered equal by the object.Equals() method called on the newly selected object (ie newlyslected.Equals(currentlySelected) ).

In this case the string.Equals method is returning true since the values of strings are equal

This is certainly a strange issue. The only workaround I can think of is storing the index of the combobox, and every time anything happens to it (KeyDown, LeftMouseButtonDown etc.) check the stored index against the new index. Something like:

public MainWindow()
{
    InitializeComponent();
    //populate combo box
    lastKnownIndex = comboBox1.SelectedIndex;
}

int lastKnownIndex;

private void comboBox1_KeyDown(object sender, KeyEventArgs e) // and all other possible input events
{
    if (comboBox1.SelectedIndex != lastKnownIndex)
    {
        //do stuff
        lastKnownIndex = comboBox1.SelectedIndex;
    }
}

There's probably a far more elegant solution but that should work.

EDIT: Should also probably let MSFT know that WPF is broken ;)

Try doing this:

ComboBoxItem newItem = new ComboBoxItem();
newItem.Content = "same item";
cmbFunctionsList.Items.Add(newItem);

Idea taken from here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM