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

标签 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>

最佳答案

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

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

关于c# - 为什么 VisualTreeHelper.GetChildrenCount 返回 0 个顶级控件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23724590/

相关文章:

c# - 无法转换为基类

c# - TextBlock TextWrapping Wrap 和 NoWrap 相结合,通过 DynamicResource 文本

c# - 修改控件模板时保留控件的主题风格

c# - 是否有Visual Studio之类的代码编辑器控件?

c# - 如何使用滚动从 WPF DataGrid 中获取所有行

c# - 获取 Unity UI 元素是否被按下

c# - Redis 用 'QUEUED' 回复所有查询

c# - 如何独立使用 Xamarin Profiler 来分析应用程序

c# - 使用 IdentityServer4 从单个客户端接受 Bearer 身份验证和 OpenIdConnect 时出现奇怪的行为

c# - 如何在 Windows 窗体的任务栏上最大化应用程序?