#997 – Possible Problems with ItemContainerGenerator

There are cases when you might use the ItemContainerGenerator type to get the corresonding ListBoxItem for a particular item in a ListBox.  For example, the code below will select every other item in a ListBox.

            // Select every other item, starting with
            // the first.
            int i = 0;
            while (i < lbNumbers.Items.Count)
            {
                // Get item's ListBoxItem
                ListBoxItem lbi = (ListBoxItem)lbNumbers.ItemContainerGenerator.ContainerFromIndex(i);
                lbi.IsSelected = true;
                i += 2;
            }

The problem with this code is that if UI virtualization is enabled for the ListBox, the ItemContainerGenerator methods will return null for items that are not currently visible.  This happens because the corresponding ListBoxItem has not yet been created.

To avoid this, you can either find an alternative method to using ItemContainerGenerator, or you can scroll the corresponding item into view before calling the method to get its container.

Advertisement

#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