locked
Listbox SelectedIndex ...out of range? RRS feed

  • Question

  • Hi:

     

    I am using a MVVM pattern to build my application. I have simple listbox which has items orientented horizontally. I am trying ot bind its "SelectedIndex" to my view model in order ot navigate the listbox with buttons..."Next" and "Previous".

    I am getting an error: "Speficied argument was out of the range of valid values. Parameter name: SelectedIndex"

    what is the issue? Do I need to wait for all items to be bound to the listbox before I set "SelectedIndex"?

    Thanks

    --tolga

     

    Monday, July 19, 2010 8:17 PM

Answers

  • Hi. I don't think that binding to SelectedIndex is good approach. When there is no selected item SelectedIndex = -1, but your items collection has no element at index -1. You need to bind to SelectedItem property, which is NULL when there is no selected items.

    For Example:

    public class BindingViewModel

    {

        ...

        public ObservableCollection<Model> Items {get; set;}

        public Model SelectedItem {get; set;}

        ...

    }

     

    And in XAML:

    ...

    <ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" .../>

    ...

    Tuesday, July 20, 2010 1:57 AM