我修改了已接受答案中的代码 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/