Silverlight浮动内容向右对齐

7

我想要一个水平的StackPanel,其中包含一些文本以及一个紧贴右侧的按钮。我尝试了以下代码:

                <StackPanel Orientation="Horizontal">
                    <TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,0,0">Ahoy!</TextBlock>
                    <Button HorizontalAlignment="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
                </StackPanel>

这似乎不起作用。显然,向TextBlock添加一个margin会起作用,像这样:

                <StackPanel Orientation="Horizontal">
                    <TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,120,0">Ahoy!</TextBlock>
                    <Button HorizontalAlignment="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
                </StackPanel>

但这样做有很多不好的原因。是否有更自然的方法来完成这个任务?


正如多位用户所指出的那样,最好的解决方案可能是使用网格(Grid)。问题:您需要什么特定的“StackPanel”行为?这将决定网格列设置。 - iCollect.it Ltd
是的,看到答案后我感到非常愚蠢。我只需要一个网格-就这么简单。我对WPF / Silverlight相当陌生。谢谢。 - Adam Rackis
3个回答

8
个人建议使用Grid代替StackPanel。只需添加两列,一列设置为 "*" 大小,另一列设置为 "Auto",并将您的 TextBlock 放在第一列,将 Button 放在第二列:

3

使用 DockPanel 替代:

<DockPanel>
    <TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,0,0">Ahoy!</TextBlock>
    <Button DockPanel.Dock="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
</DockPanel>

默认的 Dock 设置是 Left,因此它会像水平 StackPanel 一样处理那些没有明确 Dock 设置的项。

这确实是这个问题的最佳答案。 - Arturo Martinez

2

StackPanel适用于简单的场景,但如果你想完全控制布局,请使用Grid。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接