Forcing WPF to create the items in an ItemsControl

前端 未结 6 1301
日久生厌
日久生厌 2021-01-12 18:13

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

6条回答
  •  离开以前
    2021-01-12 18:18

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

提交回复
热议问题