【问题标题】:centering grid while hiding column width without reserved space在不保留空间的情况下隐藏列宽时居中网格
【发布时间】:2013-04-14 14:50:47
【问题描述】:

我有一个有两列的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;
}

【问题讨论】:

    标签: c# wpf grid


    【解决方案1】:

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

    【讨论】:

    • 如果可以的话,能不能把代码分享一下,看看你到底在尝试什么。
    • 嗨,我现在知道你到底想要做什么。只需为两列设置Width="Auto",它将始终居中。
    猜你喜欢
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 2019-08-14
    • 2019-01-30
    • 2010-09-13
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多