我有一个可见度设置为" collapse "的控件和一个ToggleButton来改变可见度之间的可见度。折叠和可见,隐藏。根据MSDN文档,当控件的可见性设置为"已折叠"时,布局中不应该为控件分配空间,但这两个枚举之间没有视觉差异。此外,控件的可见性最初设置为折叠,因此控件的初始绘图不应该为控件分配任何空间。
是否有一个概念我错过了,或者我如何让一个元素只在可见时占用空间?我的最终目标是让控件出现在基于用户选择的条件下,这些选择出现在上述显示可变控件的北部,所有控件之间的边距一致。
XAML代码片段:
<StackPanel>
<TextBox Name="hideTest" DataContext="{StaticResource persistentMemoryBridge}" Text="HIDETEST" Margin="0,327,31,491" Foreground="Black" Background="Orange" Visibility="Collapsed" />
<TextBox DataContext="{StaticResource persistentMemoryBridge}" Text="{Binding Path=PropertyTest}" Margin="0,386,31,432" Foreground="Black" Background="Yellow"/>
<ToggleButton Name="tbVisibility" Content="Toggle" Click="ToggleButton_Click" Margin="0,445,65,391"></ToggleButton>
</StackPanel>
后台代码:
private void ToggleButton_Click(object sender, RoutedEventArgs e) {
switch (hideTest.Visibility) {
case System.Windows.Visibility.Collapsed: {
hideTest.Visibility = Visibility.Hidden;
tbVisibility.Content = "Hidden";
break;
}
case System.Windows.Visibility.Hidden: {
hideTest.Visibility = Visibility.Visible;
tbVisibility.Content = "Visible";
break;
}
case System.Windows.Visibility.Visible: {
hideTest.Visibility = Visibility.Collapsed;
tbVisibility.Content = "Collapsed";
break;
}
}
}
当控件的可见性处于Collapsed
状态时,它的外边距不参与布局(与Hidden
状态相反)
可以很容易地验证:
<Window x:Class="MarginsRespectForCollapsedTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Button Margin="50,50" Visibility="Collapsed">I'm Collapsed</Button>
<Button>I'm Visible!</Button>
</StackPanel>
</Window>
我同意HighCore的观点,你的XAML看起来就像是刚刚从工具箱面板中拖出控件。VS的XAML设计器有这样一个令人不快的特性:它试图通过边距来定位控件。