wpf XAML - 如何在 StackPanel 中将控件彼此对齐

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33841945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:33:19  来源:igfitidea点击:

XAML - How do I align controls next to each other in a StackPanel

wpfxaml

提问by user1672994

So I've been trying to align the controls in the following code next to each other. But it doesn't seem to work. First I had it without the StackPanel but then I couldn't really align my Controls properly.

所以我一直在尝试将以下代码中的控件彼此对齐。但它似乎不起作用。首先我在没有 StackPanel 的情况下拥有它,但后来我无法真正正确对齐我的控件。

Here is my code:

这是我的代码:

        <StackPanel x:Name="doelenContentPanel" HorizontalAlignment="Center">
        <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  " Margin="10,58,-10,-58" HorizontalAlignment="Left" />
        <TextBox x:Name="txtbOmzet" Margin="82,58,0,0" TextWrapping="Wrap" Text="" HorizontalAlignment="Center"/>
        <TextBlock x:Name="txtBOmzetMaand" Margin="151,58,0,0" TextWrapping="Wrap" Text="Maand" HorizontalAlignment="Right" />
        </StackPanel>

采纳答案by user1672994

Got it! I added the Orientation="Horizontal"property to the StackPanel. However, this only aligns the content of this specific panel. If, for example, you want to have 2 StackPanelvertically aligned and then have the content of these 2 panels horizontally aligned, you have to do this:

知道了!我将该Orientation="Horizontal"属性添加到StackPanel. 但是,这只会对齐此特定面板的内容。例如,如果您想让StackPanel2 个面板垂直对齐,然后将这 2 个面板的内容水平对齐,则必须执行以下操作:

<StackPanel x:Name="contentWrapper" Orientation="Vertical">
    <StackPanel x:Name="doelenContentPanel" Orientation="Horizontal">
    <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  "  />
    <TextBox x:Name="txtbOmzet" TextWrapping="Wrap" Text="" />
    <TextBlock x:Name="txtBOmzetMaand" TextWrapping="Wrap" Text="Maand" />
</StackPanel>
<StackPanel x:Name="secondPanel" Orientation="Horizontal">
    *this looks familiar to the first panel*
</StackPanel>

回答by user1672994

First, don't use the hardcoded Marginproperty and second remove the HorizontalAlignmentfrom each control. Now to align the control next to each other, set the Orientation property of StackPanel

首先,不要使用硬编码Margin属性,然后HorizontalAlignment从每个控件中删除。现在要将控件彼此对齐,请设置 Orientation 属性StackPanel

<StackPanel x:Name="doelenContentPanel" Orientation="Horizontal">
  <TextBlock x:Name="txtBOmzet" TextWrapping="Wrap" Text="Omzet:  "  />
  <TextBox x:Name="txtbOmzet" TextWrapping="Wrap" Text="" />
  <TextBlock x:Name="txtBOmzetMaand" TextWrapping="Wrap" Text="Maand" />
</StackPanel>