VisualTreeHelper.GetChildrenCount return 0?

前端 未结 2 1857
闹比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:05

    If your using Caliburn.Micro this will help you. For your Viewmodel the base Class should be Screen then only VisualTreeHelper.GetChildrenCount() give no.of childs.(because Screen will Activate all childs

    or otherwise (FrameworkElement)YourParent).ApplyTemplate() method

    0 讨论(0)
  • 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<object>().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;
        ...
    }
    
    0 讨论(0)
提交回复
热议问题