WPF - 如何将水平排列的StackPanel中的TextBlock右对齐?

23

这应该很简单 - 我已经把头撞在桌子上很长时间,试图让一个看起来简单的任务工作(让我觉得WPF不直观或有bug)......

无论如何,我有一个设置为水平方向的Stackpanel,在其中有两个TextBlocks。我希望第二个TextBlock将其文本显示到右侧。

我该怎么做呢?

做所有这些让我想起了我为什么放弃了Silverlight。 :p

3个回答

35

如果您不想像StackPanel那样堆叠所有元素,则需要使用DockPanel。为了使第二个TextBlock右对齐,您可以添加一个额外的虚拟TextBlock来填充它们之间的区域:

    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock DockPanel.Dock="Right">Right text</TextBlock>
        <TextBlock />
    </DockPanel>
或者你可以使用属性:
    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock TextAlignment="Right">Right text</TextBlock>
    </DockPanel>

工作了!感谢您的时间和努力 :) - Ahmed Mahmoud
超级快速并且有效。我赞扬你花时间分享这个。希望你能在地上找到5美元。 - Chris

4
使用网格非常容易实现,我也遇到了同样的问题 :)
<Grid>
    <TextBlock>Left text</TextBlock>
    <TextBlock TextAlignment="Right">Right text</TextBlock>
</Grid>

2

针对您的评论,这里提供了另一个示例,展示了实现您所需的两种方式,即网格布局和停靠面板布局。根据描述,停靠面板布局可能是您需要的。如果不行,请提供更清晰的关于所需布局和属性的描述。

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="0.45*" />   
    <RowDefinition Height="0.05*" />
    <RowDefinition Height="0.45*" />
  </Grid.RowDefinitions>
   <Grid Grid.Row="0">
      <Grid.ColumnDefinitions>
        <!-- note: you don't need to declare ColumnDefintion
         widths here; added for clarity. -->
         <ColumnDefinition Width="0.5*" />
         <ColumnDefinition Width="0.5*" />
      </Grid.ColumnDefinitions>
      <TextBlock 
          Grid.Column="0" 
          Background="Tomato" 
          TextWrapping="Wrap">I'm on the left</TextBlock>
      <TextBlock
          Grid.Column="1"
          Background="Yellow"
          TextAlignment="Right"
          TextWrapping="Wrap">I'm on the right</TextBlock>
   </Grid>

   <Grid Grid.Row="1" Background="Gray" />

   <DockPanel Grid.Row="2">
      <TextBlock
          DockPanel.Dock="Left"
          Background="Tomato" 
          TextWrapping="Wrap">I'm on the left</TextBlock>
      <TextBlock
          DockPanel.Dock="Right"
          Background="Yellow"
          TextAlignment="Right"
          TextWrapping="Wrap">I'm on the right</TextBlock>
   </DockPanel>
</Grid>
</Page>

有没有办法在不明确定义宽度的情况下完成?我希望表格能够拉伸以填充任何区域。这是我一直遇到的问题之一 - 我还没有找到一种方法来说“宽度=100%”。 - bugfixr
由于您的StackPanel具有水平方向,所以只有TextBlocks会水平堆叠。如果没有宽度,TextBlock将根据其内容调整大小。一些想法:删除TextBlock宽度并将StackPanel设置为Orientation="Vertical",每个TextBlock现在将占用StackPanel可用宽度的100%。或者,您可以尝试使用Grid布局进行实验。不知道您对布局的确切要求,这有点猜测游戏。 - Metro Smurf
1
我认为他可能需要的不是一个StackPanel(因为你提到的原因),但对于他所讲述的简单布局,我建议使用DockPanel而不是Grid。 - itowlson
即使使用DockPanel,这也不完全符合我的期望。在HTML中,可以通过创建一个100%的表格,添加两列,并将第二列对齐到右侧来实现此效果。这样一个简单的事情,在WPF中似乎并不容易实现... - bugfixr

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