[WPF]: Strange problem with ListBox

advertisements

I have a weird problem with a ListBox in Wpf, where I have a binding to the ListBox SelectedIndex to a property in the viewModel object.

If the SelectedIndex is less that zero, none of the listbox items are selected. However, if the SelectedIndex is set to a larger number than the actual size of the list, the last item is still selected!

Is there a way to make the listBox not select the last item when the SelectedIndex is set to a higher value than the last items index?

Thanks


By convention, a SelectedIndex of -1 signifies no selection; that's why negative values don't result in a selection in the listbox.

To control the selection more closely, you could bind to an ICollectionView instead of directly to the collection (in fact it's what I'd always recommend when doing MVVM), and control the selection with the yourView.MoveCurrentTo... methods. Example:

ListCollectionView cv = new ListCollectionView(sourceCollection); // bind the listbox's ItemsSource to this
cv.MoveCurrentTo(null); // no selection;
cv.MoveCurrentToLast();