views:

77

answers:

1

How can I select multiple items from the listbox in a windows phone 7 application? e.g

listboxName.SelectedIndex = 0;
listboxName.SelectedIndex = 1;
listboxName.SelectedIndex = 2;

The above code selects 2 while I need to select all three of those.

The values I need to preselect are given to me in a array like {true,true,true,false,false}

So I tried the using IsSelected like shown below... doesn't work.

     int i = 0;
     foreach (ListBoxItem currentItem in listboxName.SelectedItems)
            {
                if (tagindexeselected[i])
                {
                    currentItem.IsSelected = true;
                }
                i++;
            }

What would be the proper way to select multiple items in a listbox?

+1  A: 

Hard to say there's a single, best way - it depends on how you're populating your list box, etc. First, be sure your list box's Selection Mode is set to Multiple or Extended.

One option is to use the ListBox's SelectedItems collection:

        listBox1.SelectedItems.Add(listBox1.Items[0]);
        listBox1.SelectedItems.Add(listBox1.Items[1]);
        listBox1.SelectedItems.Add(listBox1.Items[2]);

Note also, in your example above, you're iterating over the SelectedItems collection - not the Items collection. If nothing is selected, that's an empty collection. Also, if your list box ItemsSource is not a series of ListBox Items (you can set your itemsSource to almost any enumeration), you will get an InvalidCastException when you go to run your foreach statement.

avidgator