给定一个StackPanel:
<StackPanel>
<TextBox Height="30">Apple</TextBox>
<TextBox Height="80">Banana</TextBox>
<TextBox Height="120">Cherry</TextBox>
</StackPanel>
在子元素本身大小不同的情况下,怎样才能使它们之间的间隔大小相等呢?在不为每个单独的子节点设置属性的情况下可以做到这一点吗?
给定一个StackPanel:
<StackPanel>
<TextBox Height="30">Apple</TextBox>
<TextBox Height="80">Banana</TextBox>
<TextBox Height="120">Cherry</TextBox>
</StackPanel>
在子元素本身大小不同的情况下,怎样才能使它们之间的间隔大小相等呢?在不为每个单独的子节点设置属性的情况下可以做到这一点吗?
当前回答
Sergey的答案是+1。如果你想把它应用到所有的stackpanel,你可以这样做:
<Style TargetType="{x:Type StackPanel}">
<Style.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="{StaticResource tbMargin}"/>
</Style>
</Style.Resources>
</Style>
但是要注意:如果你在App.xaml(或合并到Application.Resources中的另一个字典)中定义了这样的样式,它会覆盖控件的默认样式。对于大多数无外观的控件,如堆栈面板,这不是一个问题,但对于文本框等,你可能会偶然发现这个问题,幸运的是有一些变通办法。
其他回答
网格。列空间网格。StackPanel行空间。间距现在在UWP预览,所有将允许更好地完成这里的要求。
这些属性目前只与Windows 10秋季创作者更新内部SDK可用,但应该使它到最后位!
使用Margin或Padding,应用于容器内的作用域:
<StackPanel>
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="0,10,0,0"/>
</Style>
</StackPanel.Resources>
<TextBox Text="Apple"/>
<TextBox Text="Banana"/>
<TextBox Text="Cherry"/>
</StackPanel>
编辑:如果你想在两个容器之间重用边距,你可以将边距值转换为外部作用域中的资源,例如。
<Window.Resources>
<Thickness x:Key="tbMargin">0,10,0,0</Thickness>
</Window.Resources>
然后在内部作用域中引用这个值
<StackPanel.Resources>
<Style TargetType="{x:Type TextBox}">
<Setter Property="Margin" Value="{StaticResource tbMargin}"/>
</Style>
</StackPanel.Resources>
UniformGrid可能在Silverlight中无法使用,但有人已经从WPF中移植了它。http://www.jeff.wilcox.name/2009/01/uniform-grid/
有时你需要设置填充,而不是边距,使项目之间的空间小于默认值
通常,我使用Grid而不是这样的StackPanel:
水平情况
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox Height="30" Grid.Column="0">Apple</TextBox>
<TextBox Height="80" Grid.Column="2">Banana</TextBox>
<TextBox Height="120" Grid.Column="4">Cherry</TextBox>
</Grid>
垂直的情况下
<Grid>
<Grid.ColumnDefinitions>
<RowDefinition Width="auto"/>
<RowDefinition Width="*"/>
<RowDefinition Width="auto"/>
<RowDefinition Width="*"/>
<RowDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<TextBox Height="30" Grid.Row="0">Apple</TextBox>
<TextBox Height="80" Grid.Row="2">Banana</TextBox>
<TextBox Height="120" Grid.Row="4">Cherry</TextBox>
</Grid>