如何从代码中获取StackPanel的孩子StackPanel?

时间:2015-02-20 12:23:25

标签: wpf

以下是我的StackPanel"群组",我希望我的孩子stackPanel可见状态更改为可见,但在代码隐藏中,我没有看到子堆栈面板&# 39;的名字。

这只是伪:

<StackPanel X.Name="MainStack">
  <Grid>
    <Grid.ColumnDefinitions>
       <ColumnDefinition Width="1*"></ColumnDefinition>
       <ColumnDefinition Width="6*"></ColumnDefinition>
       <ColumnDefinition Width="1.3*"></ColumnDefinition>
       <ColumnDefinition Width="1.5*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
       <StackPanel Grid.Column="0">
             something...              
       </StackPanel>
      <StackPanel x:name="Stack" Grid.Column="1" Visibility=Collapsed>
             something...              
       </StackPanel>
       <StackPanel Grid.Column="2">
             something...              
       </StackPanel>
  </Grid>
</StackPanel>

我正在尝试从代码中将可见性更改为Visible但我不能。

MainStack.Children(Stack.Visibility = Visibility.Visible);

没有MainStack.Children,程序没有看到子堆栈名称。

1 个答案:

答案 0 :(得分:-2)

更新答案以涵盖递归子查找。

你可以做类似的事情 -

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj)     where T : DependencyObject
{
    if (depObj != null)
{
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
    {
        DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
        if (child != null && child is T)
        {
            yield return (T)child;
        }

        foreach (T childOfChild in FindVisualChildren<T>(child))
        {
            yield return childOfChild;
        }
    }
}

}

foreach (var p in FindVisualChildren<StackPanel>(MainStack))
{
    p.Visibility = Visibility.Visible;
}