如何将 StackPanel 的子元素隔开? [英] How do I space out the child elements of a StackPanel?

查看:21
本文介绍了如何将 StackPanel 的子元素隔开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 StackPanel:

Given a StackPanel:

<StackPanel>
  <TextBox Height="30">Apple</TextBox>
  <TextBox Height="80">Banana</TextBox>
  <TextBox Height="120">Cherry</TextBox>
</StackPanel>

将子元素隔开以使它们之间具有相同大小的间隙的最佳方法是什么,即使子元素本身具有不同的大小?可以在不为每个单独的孩子设置属性的情况下完成吗?

What's the best way to space out the child elements so that there are equally-sized gaps between them, even though the child elements themselves are of different sizes? Can it be done without setting properties on each of the individual children?

推荐答案

Use Margin or Padding,应用于容器内的作用域:

Use Margin or Padding, applied to the scope within the container:

<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>

如果您想重复使用两个容器之间的边距,您可以将边距值转换为外部范围内的资源,例如

In case you would want to re-use the margin between two containers, you can convert the margin value to a resource in an outer scope, f.e.

<Window.Resources>
    <Thickness x:Key="tbMargin">0,10,0,0</Thickness>
</Window.Resources>

然后在内部作用域中引用这个值

and then refer to this value in the inner scope

<StackPanel.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="Margin" Value="{StaticResource tbMargin}"/>
    </Style>
</StackPanel.Resources>

这篇关于如何将 StackPanel 的子元素隔开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆