title: listBox selectedIndex is always 0 unless I make the thread wait
body: <p>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: <a href="https://stackoverflow.com/questions/20025742/wpf-listbox-selectionchanged-event">WPF ListBox SelectionChanged event</a> and the suggestion to make the thread sleep for 70ms works most of the time. 200ms works even more reliably!!</p>
  
  <p>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.</p>
  
  <p>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:</p>
  
  <pre><code>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;
          }
      }
  </code></pre>
  
  <p>Any advice gratefully received.</p>
  
  <p>in response to KANAX I added a Console output of the SelectedIndex and got this when I selected the 5th item:</p>
  
  <p><a href="https://i.stack.imgur.com/iC4Ab.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iC4Ab.png" alt="enter image description here"></a></p>
  
  <p>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?</p>