#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

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #997 – Possible Problems with ItemContainerGenerator

  1. Pingback: Dew Drop – January 29, 2014 (#1712) | Morning Dew

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: