#979 – Selecting Items in a ListBox Programmatically
January 3, 2014 5 Comments
The ListBoxItem object, representing a single item in a ListBox, contains an IsSelected property that you can read in order to determine whether the item is selected. The IsSelected property can be read from to determine if the item is selected. It can also be written to, to select the item.
The code below selects every other item in a ListBox. Note that we need to call the ItemContainerGenerator.ContainerFromIndex helper method in order to get the ListBoxItem for each item.
private void btnWrite_Click(object sender, RoutedEventArgs e) { // Select every other item, starting with // the first. int i = 0; while (i < lbActors.Items.Count) { // Get item's ListBoxItem ListBoxItem lbi = (ListBoxItem)lbActors.ItemContainerGenerator.ContainerFromIndex(i); lbi.IsSelected = true; i += 2; } }