StackPanel儿童改变时如何重新计算大小?

时间:2014-05-28 14:13:37

标签: c# xaml windows-phone-8

我有一个Grid标题为StackPanel,在XAML中是这样的:

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel x:Name="HeaderPanel" Grid.Row="0">
            <Rectangle Height="100" Fill="Red" />
        </StackPanel>
        <Rectangle Fill="Blue" Grid.Row="1" />
    </Grid>

当我删除C#代码中的红色矩形时:

        HeaderPanel.Children.Clear()

它消失但仍占用空间。我预计Auto高度StackPanel应该折叠为0,蓝色矩形占据网格的所有空间。我可以重新计算尺寸吗?

平台是Windows Phone 8。

2 个答案:

答案 0 :(得分:0)

受到Chris W.s评论的启发,这就是我解决它的方式。我将XAML改为:

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Rectangle Height="100" Fill="Red" x:Name="Header" Grid.Row="0"/>
        <Rectangle Fill="Blue" Grid.Row="1" />
    </Grid>

然后在代码中我做:

        ContentPanel.Children.Remove(Header);

如果我想添加其他标题:

        Rectangle r2 = new Rectangle();
        r2.Fill = new SolidColorBrush(Colors.Green);
        r2.SetValue(Grid.RowProperty, 0);
        r2.Height = 50;
        ContentPanel.Children.Add(r2);

答案 1 :(得分:0)

我在Windows Phone Silverlight项目中遇到过这种情况。我真的想保留StackPanels,所以我找到了一个高度属性的解决方法。我有一个用UIElements填充堆栈面板的方法:

private void LayoutStackPanel(IEnumerable<UIElement> elements)
{
    stackPanel.Children.Clear();
    if (elements.Count == 0)
    {
        stackPanel.Height = 0;
    }
    else
    {
        // height must be removed or ui elements will overlap
        stackPanel.ClearValue(StackPanel.HeightProperty);
        foreach (var element in elements)
        {
            stackPanel.Children.Add(element);
        }
    }
}

我只在Windows Phone上测试过,但我认为它也适用于WPF。