WPF 中 StackPanel 控件的可视化 Visibility.Collapsed 控件元素会自动前移_控件

XAML:

<Grid>
   <Grid.RowDefinitions>
       <RowDefinition/>
       <RowDefinition  Height="Auto"/>
   </Grid.RowDefinitions>
   <StackPanel Grid.Row="0">
       <TextBox x:Name="txb_001" Height="30" Width="50"/>
       <TextBlock x:Name="txt_HiddenElem" Text="隐藏元素测试" HorizontalAlignment="Center"/>
       <Button x:Name="btn_Set001" Content="Set 001"  Click="btn_Set001_Click" Height="30" Width="50"/>
       <Button x:Name="btn_HumanTest" Click="btn_HumanTest_Click" Content="Human 测试" Height="40" Width="100" />
   </StackPanel>
   <Button Margin="3" Grid.Row="1" Content="隐藏" x:Name="btn_Hidden_Elem" Click="btn_Hidden_Elem_Click" Height="30" Width="80"/>
</Grid>
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.

Code behind:

隐藏按钮:

private void btn_Hidden_Elem_Click(object sender, RoutedEventArgs e)
{
    txt_HiddenElem.Visibility = txt_HiddenElem.Visibility == Visibility.Collapsed
        ? Visibility.Visible : Visibility.Collapsed;
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

txt_HiddenElem 控件 Collapsed 之后,下面的 btn_Set001 控件会自动向前移动。如下效果:

WPF 中 StackPanel 控件的可视化 Visibility.Collapsed 控件元素会自动前移_sed_02

如果是Visibility.Hidden的话,不会出现上面的效果,而只是隐藏,表现出来的是空白。