VisualTreeHelper.GetChildrenCount return 0?

前端 未结 2 1856
闹比i
闹比i 2021-02-07 17:45

I\'m using VisualTreeHelper.GetChildrenCount() to find child controls, but it always return 0.

Here is my code



        
2条回答
  •  时光说笑
    2021-02-07 18:12

    The problem is that when the ItemContainerGenerator signals the ContainersGenerated status, the container (a ContentPresenter) has been created, but not yet loaded. Especially the data template has not yet been applied to the ContentPresenter, hence there is nothing in the visual tree.

    You may get around this by adding a Loaded event handler when looping over the generated containers.

    private void ItemContainerGeneratorStatusChanged(object sender, EventArgs e)
    {
        if (itemsControl.ItemContainerGenerator.Status
            == GeneratorStatus.ContainersGenerated)
        {
            var containers = itemsControl.Items.Cast().Select(
                item => (FrameworkElement)itemsControl
                    .ItemContainerGenerator.ContainerFromItem(item));
    
            foreach (var container in containers)
            {
                container.Loaded += ItemContainerLoaded;
            }
        }
    }
    
    private void ItemContainerLoaded(object sender, RoutedEventArgs e)
    {
        var element = (FrameworkElement)sender;
        element.Loaded -= ItemContainerLoaded;
    
        var grid = VisualTreeHelper.GetChild(element, 0) as Grid;
        ...
    }
    
        

    提交回复
    热议问题