在没有保留空间的情况下隐藏列宽而居中网格

时间:2013-04-14 14:50:48

标签: c# wpf grid

我有一个Grid,有两列。我想要隐藏第二列,直到在第一列中单击Button。问题是:

如果我将可见性设置为在第二列上折叠,则不会显示该元素,也不会在布局中为其预留空间,从而导致第二列可见时网格不居中。

如果我将可见性设置为隐藏,则不会显示该元素,但会为布局中的元素保留空间,使其居中但显示第1列可见时我不想要的保留空间和第2列不是。

我想要介于两者之间。例如,仅显示第一列和中心整个网格。当还显示第二列时,再次将整个网格居中。

这有意义吗?

XAML

<Grid>
    <Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"  />
    <ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
    <RowDefinition Height="auto" />
    <RowDefinition Height="auto" />
</Grid.RowDefinitions>

    <Label  Content="Show second column on grid" Width="300"
                FontStyle="Italic" 
                FontWeight="Bold"
                Grid.Column="0" 
                Grid.Row="0"
                HorizontalAlignment="center"
                Foreground="White"/>
    <Button Content="Click Me" 
                Width="75" 
                Margin="5" 
                Grid.Column="0" 
                Grid.Row="1" Click="Button_Click" />
    <StackPanel x:Name="showSecondColumn" 
                Grid.Column="1" 
                Grid.Row="0"
                Grid.RowSpan="2"
                Margin="5,0,0,0" 
                Orientation="Vertical" 
                Background="Red" Visibility="Collapsed">
        <Label Content="Second column is shown" 
               Background="Red" />
        <Label Content="Another item inside second column" 
               BorderBrush="Red" 
               BorderThickness="3" 
               Margin="0,5" 
               Background="White" />
    </StackPanel>
</Grid>

Code behind

private void Button_Click(object sender, RoutedEventArgs e)
{
    showSecondColumn.Visibility = Visibility.Visible;
}

1 个答案:

答案 0 :(得分:0)

尝试不同的方法怎么样? 您可以有两列,一列width="*"(以便它占用所有可用空间),并将第二列的宽度设置为width="Auto"。 然后在第二列中,默认情况下,您可以将visibility设置为collapsed的控件/容器放置。点击按钮,您可以根据需要进行切换。