在GridSplitter下折叠控制 - 出现不需要的空白区域

时间:2014-07-31 09:41:13

标签: c# wpf

给出以下XAML;

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition MinHeight="100"/>
        <RowDefinition Height="2"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <Border Grid.Row="0"
            Background="LightBlue">
        <Button Height="30"
                Click="Button_Click">Hide Lower Panel</Button>
    </Border>
    <GridSplitter Grid.Row="1"
                  ResizeDirection="Rows" 
                  Width="Auto"
                  HorizontalAlignment="Stretch"
                  Margin="0"
                  x:Name="Splitter"/>
    <Border Grid.Row="2"
            Background="LightCoral"
            x:Name="LowerPanel" MinHeight="25"/>
</Grid>

Button_Click的位置;

this.LowerPanel.Visibility = this.LowerPanel.Visibility == Visibility.Visible 
    ? Visibility.Collapsed 
    : Visibility.Visible;

这看起来像这样;

enter image description here

如果在执行任何其他操作之前单击该按钮,则会按预期折叠;

enter image description here

但是,如果我使用网格分割器调整大小..

enter image description here

然后当我按下按钮时,会发生以下情况;

enter image description here

有没有办法让下面的元素在调整大小后再次正确折叠?

注意:出于这个问题的目的,我只使用了代码隐藏的事件处理程序和一个按钮来触发它,但在现实生活中,它以适当的MVVM方式完成,可见性为由视图模型上的绑定属性确定。

2 个答案:

答案 0 :(得分:5)

AFAIK,当使用GridSplitter时,它会重写相应RowDefinitions和ColumnDefinitions的Height或Width属性。为了做你想做的事,你应该使用RowDefinitions.Height属性,如下所示:

public MainWindow()
{
    InitializeComponent();
    //gr is the name of the Grid
    basepr1 = gr.RowDefinitions[0].Height;
    basepr2 = gr.RowDefinitions[2].Height;
}
static GridLength zero = new GridLength(0);
GridLength basepr1;
GridLength basepr2;
private void Button_Click(object sender, RoutedEventArgs e)
{
    if (this.LowerPanel.Visibility == Visibility.Visible)
    {
        this.LowerPanel.Visibility = Visibility.Collapsed;
        basepr2 = gr.RowDefinitions[2].Height; // remember previos height
        gr.RowDefinitions[2].Height = zero;
    }
    else
    {
        this.LowerPanel.Visibility = Visibility.Visible;
        gr.RowDefinitions[2].Height = basepr2;
    }
}

答案 1 :(得分:0)

我认为你需要将其中一个行定义标记为'*':

<Grid.RowDefinitions>
    <RowDefinition MinHeight="100"/>
    <RowDefinition Height="2"/>
    <RowDefinition Height="*"/>
</Grid.RowDefinitions>