代码之家  ›  专栏  ›  技术社区  ›  bugfixr

wpf-如何在水平方向的stackpanel中右对齐文本块?

  •  17
  • bugfixr  · 技术社区  · 16 年前

    这应该很简单-我已经用头撞我的桌子这么长时间试图使一个看似简单的任务工作(使我觉得wpf是不直观或错误的)……

    无论如何,我有一个StackPanel,它被设置为水平方向。里面有两个文本块。我要第二个在右边显示文字。

    我该怎么做?

    这么做让我想起了为什么我要离开Silverlight。P

    3 回复  |  直到 8 年前
        1
  •  30
  •   splintor    15 年前

    如果不希望所有元素都像stackpanel那样堆叠,则需要使用dockpanel。要使第二个文本块右对齐,可以添加额外的虚拟文本块来填充它们之间的区域:

        <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>
    
        2
  •  2
  •   Metro Smurf    16 年前

    根据您的评论,下面是另一个例子,展示了实现您所需的两种方法:网格布局和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>
    
        3
  •  1
  •   Vishal    10 年前

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

    <Grid>
        <TextBlock>Left text</TextBlock>
        <TextBlock TextAlignment="Right">Right text</TextBlock>
    </Grid>