为什么VisualTreeHelper.GetChildrenCount返回0个顶级控件?

时间:2014-05-18 17:04:40

标签: c# wpf

我修改了接受的答案here中的代码,以返回第一个找到的某种类型的控件。但是当我尝试从窗口本身开始遍历时,VisualTreeHelper.GetChildrenCount会返回0,尽管它上面放了一个网格。我所做的修改对结果没有影响。

以下是我如何称呼该方法:

DockPanel panel = UIHelper.FindFirstChild<DockPanel>(this);

这是我的XAML代码:

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="216" Width="267">
    <Grid>
        <DockPanel Height="200" Width="250">
            <StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Background="LightBlue">
                <Button Content="01" Margin="1 1 15 1"/>
                <Button Content="02" Margin="1"/>
                <Button Content="03" Margin="1"/>
            </StackPanel>

            <StackPanel Orientation="Horizontal" Height="25" DockPanel.Dock="Bottom" Background="LightBlue">
                <TextBlock VerticalAlignment="Center">Processing...</TextBlock>
                <ProgressBar Value="75" Width="100" Margin="4"/>
            </StackPanel>

            <Grid>
                <TextBlock>Content area</TextBlock>
            </Grid>
        </DockPanel>
    </Grid>    
</Window>

1 个答案:

答案 0 :(得分:5)

因为你在构造函数中调用它,所以可视化树还没有准备好。您应该在Window.Loaded事件中调用它

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    DockPanel panel = UIHelper.FindFirstChild<DockPanel>(this);
    Console.WriteLine(VisualTreeHelper.GetChildrenCount(panel)); //returns 3
}