listBox selectedIndex is always 0 unless I make th

2019-09-09 22:53发布

问题:

I have a listBox populated manually. When a user selects an item I use the value of the selected index to recreate the list with new data. However, it always seems to return 0 unless I put a breakpoint in. With the breakpoint it works perfectly. I looked at the question: WPF ListBox SelectionChanged event and the suggestion to make the thread sleep for 70ms works most of the time. 200ms works even more reliably!!

I am guessing this is a threading issue but I don't know how to make the event handler wait for the selection event to finish properly other than Thread.Sleep() which is obviously unsatisfactory.

I tried to use e.AddedItems but that had the same problem - no AddedItems until the event completed. I had to make the thread sleep to ensure there was something to work on. This is my code for the event handler:

private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (listBox.SelectedIndex != -1)
        {
            selectedTopicID = listBox.SelectedIndex;
            listBox.Items.Clear();  //Breakpoint at start of line will fix issue
            foreach (Skill skill in setOfSkills)
            {
                if (skill.topicID == selectedTopicID)
                {
                    string skillName = skill.skillName;
                    ListBoxItem nextSkill = new ListBoxItem();
                    nextSkill.Content = skillName;
                    nextSkill.Height = 50;
                    listBox.Items.Insert(0, nextSkill);
                }
            }
            currentList = CurrentListType.Skill;
        }
    }

Any advice gratefully received.

in response to KANAX I added a Console output of the SelectedIndex and got this when I selected the 5th item:

The App is then displaying the contents from the first item. Additional edit: I am suspicious of the role of listbox.Items.Clear(). I need it if I am to replace the contents, but is it triggering a call to SelectionChanged with unpredictable results?

回答1:

selectionchanged event executes just before change of index. you should go with SelectedIndexChanged event to fulfill you need.

Check this, https://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindexchanged(v=vs.110).aspx



回答2:

I have given up trying to control the flow of selectionChanged events. I am fairly sure my problem lay with ListBox.Items.Clear(). I solved my own problem by not overwriting the list but writing new entries based on the original selection in a different ListBox.

I want to keep the old entries, but you could clear them after the new one is written if need be.