21

这应该很简单 - 我一直在用我的头撞我的桌子很长时间试图让一个看似简单的任务工作(让我觉得 WPF 不直观或有问题)......

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

我该如何完成它?

做这一切让我想起了为什么我离开了 Silverlight。:p

4

3 回答 3

35

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

    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock DockPanel.Dock="Right">Right text</TextBlock>
        <TextBlock />
    </DockPanel>

或者您可以使用TextAlignment属性:

    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock TextAlignment="Right">Right text</TextBlock>
    </DockPanel>
于 2010-06-30T09:07:36.473 回答
4

它可以通过使用网格很容易地存档,因为我遇到了同样的问题:)

<Grid>
    <TextBlock>Left text</TextBlock>
    <TextBlock TextAlignment="Right">Right text</TextBlock>
</Grid>
于 2015-02-03T05:49:31.820 回答
2

根据您的评论,这里是另一个示例,显示了实现您想要的几种方法,网格布局和 DockPanel 布局。从它的声音来看,DockPanel 布局可能就是您正在寻找的。如果这不起作用,您可能需要对所需的布局和属性提供更清晰的描述。

<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>
于 2009-10-17T18:34:51.637 回答