I want to verify that the items in my ListBox
are displayed correctly in the UI. I figured one way to do this is to go through all of the children of the
In my case, I found that calling UpdateLayout()
on the ItemsControl
(ListBox
, ListView
, etc.) started up its ItemContainerGenerator
, such that the generator's status changed from "NotStarted" to "GeneratingContainers", and null
containers were no longer being returned by ItemContainerGenerator.ContainerFromItem
and/or ItemContainerGenerator.ContainerFromIndex
.
For example:
public static bool FocusSelectedItem(this ListBox listbox)
{
int ix;
if ((ix = listbox.SelectedIndex) < 0)
return false;
var icg = listbox.ItemContainerGenerator;
if (icg.Status == GeneratorStatus.NotStarted)
listbox.UpdateLayout();
var el = (UIElement)icg.ContainerFromIndex(ix);
if (el == null)
return false;
listbox.ScrollIntoView(el);
return el == Keyboard.Focus(el);
}