除非我让线程等待,否则listBox selectedIndex始终为0 [英] listBox selectedIndex is always 0 unless I make the thread wait

查看:65
本文介绍了除非我让线程等待,否则listBox selectedIndex始终为0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个手动填充的listBox.当用户选择一个项目时,我将使用所选索引的值来使用新数据重新创建列表.但是,除非我输入了断点,否则它似乎总是返回0.有了断点,它可以完美地工作.我看了一个问题: WPF ListBox SelectionChanged事件和使线程休眠70ms的建议大部分时间都可以正常工作. 200ms更可靠地工作!!

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

我猜这是一个线程问题,但是我不知道如何使事件处理程序等待选择事件正常完成,而Thread.Sleep()显然不尽人意.

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.

我尝试使用e.AddedItems,但是存在相同的问题-在事件完成之前,没有AddedItems.我必须使线程休眠,以确保有需要处理的东西.这是我的事件处理程序代码:

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.

作为对KANAX的响应,我添加了SelectedIndex的控制台输出,并在选择第五项时得到了它:

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

然后,该应用程序将显示第一项的内容. 附加我怀疑listbox.Items.Clear()的角色.如果我要替换内容,则需要它,但是它会触发对SelectionChanged的调用,但结果无法预测?

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?

推荐答案

selectionchanged事件在更改索引之前执行.您应该使用SelectedIndexChanged事件来满足您的需求.

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

选中此选项, 查看全文

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆