title: WPF Deleting item from listbox
body: <p>I have a listbox in WPF that's bound to a ObservableCollection using the ItemSource property. This works fine, the correct items are shown.</p>
  
  <p>The listbox (which contains a list of image names) has an event handler on the SelectionChanged event which updates the source of an Image control with the path to the selected image (effectively giving an image preview).</p>
  
  <p>I have the following code to remove an item from the lisbox, on a button's click event:</p>
  
  <pre><code>if (lstLocal.SelectedIndex &gt; -1)
  {
      localImages.RemoveAt(lstLocal.SelectedIndex);
  }
  </code></pre>
  
  <p>localImages being the <code>ObservableCollection</code> and lstLocal being the <code>ListBox</code>.</p>
  
  <p>However, when I remove the selected item this causes the SelectionChanged event to fire. My SelectionChanged event handler makes use of the SelectedIndex property on the listbox. I get the exeption <code>Index was out of range. Must be non-negative and less than the size of the collection.</code> , so I'm guessing that removing an item causes SelectedIndex to be set to something like null (or a negative number)?</p>
  
  <p>Is there a way around this problem? I'm guessing there's a better way for me to remove items, or I need some sort of check on my SelectionChanged handler?</p>