Unable to select multiple items from a listbox in a Windows Phone 7 application
How can I select multiple items from the listbox in a Windows Phone 7 applicati开发者_运维问答on? 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?
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.
foreach (DataRowView item in lstServer.SelectedItems) {
string WebServerIP = item[lstServer.DisplayMember].ToString();
string WebServerUrl = item[lstServer.ValueMember].ToString();
_WebObjIgent.Url = WebServerUrl;
}
Note : lstServer is Listbox of window application . By using Displaymember and valuemember proprty you can access value and text of listbox.
精彩评论