#979 – Selecting Items in a ListBox Programmatically

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;
    }
}

979-001

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

2 Responses to #979 – Selecting Items in a ListBox Programmatically

  1. Pingback: Dew Drop – January 3, 2014 (#1694) | Morning Dew

  2. Per Eriksson says:

    Great post!!! One line of code to solve a problem that all other sites suggest can only be solved with template changes etc etc

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: