#978 – Discovering Whether an Item in a ListBox Is Selected

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.

If you use data binding to populate the list, the objects in the ListBox’s Items property will not be ListBoxItem instances, but will have a type matching the bound object.

You can use the ContainerFromItem helper method to get the corresponding ListBoxItem so that you can then query it to determine if the object is selected.

        private void btnRead_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder sbInfo = new StringBuilder();

            // Each item is an Actor
            foreach (Actor a in lbActors.Items)
            {
                // Get item's ListBoxItem
                ListBoxItem lbi =
                  (ListBoxItem)lbActors.ItemContainerGenerator.ContainerFromItem(a);

                if (lbi.IsSelected)
                    sbInfo.Append("YES ");
                else
                    sbInfo.Append("no ");
            }

            MessageBox.Show(sbInfo.ToString());
        }

978-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.

3 Responses to #978 – Discovering Whether an Item in a ListBox Is Selected

  1. Andrei Rinea says:

    As far as I remember this method works as long as the item is in the viewport or at least virtualization is not enabled. Trying to obtain the view item (that is ListBoxItem in this case) for a virtualizing ItemsControl (ListBox in this case) which is not in the view port will usually yield null.

  2. Andrei Rinea says:

    As far as I remember if virtualization is enabled and the item is not in the view port, ContainerFromItem will yield null. Are you sure this works with virtualization?

  3. Andrei Rinea says:

    … and as far as I experimented just now (.NET 4.5) virtualization is on by default.

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: