tags:

views:

47

answers:

2

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

+3  A: 

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();
Alex Paven
A: 

One idea might be to disallow the selected index to be greater than the last index.

public IEnumerable<object> Items {get; protected set;} //your collection
private int m_selectedIndex; //the underlying data for your new property

private int SelectedIndex //bind the SelectedIndex property of the listbox to this
{
    get { return m_index; }
    set
    {
        if (value < Items.Count -1)
            m_index = value;
        else
            m_index = -1;

        PropertyChanged(...)
    }
}
Val