WPF - 如何在水平方向的堆栈面板内对齐文本块?

bug*_*ixr 17 wpf xaml textblock stackpanel .net-3.5

这应该是这么简单 - 我一直在我的桌子上长时间试图让一个看似简单的任务工作(让我觉得WPF不直观或有缺陷)......

在任何情况下,我都有一个设置为水平方向的Stackpanel.在里面我有两个TextBlocks.我希望第二个在右边显示它的文本.

我该如何完成它?

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

spl*_*tor 30

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

    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock DockPanel.Dock="Right">Right text</TextBlock>
        <TextBlock />
    </DockPanel>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用TextAlignment属性:

    <DockPanel>
        <TextBlock>Left text</TextBlock>
        <TextBlock TextAlignment="Right">Right text</TextBlock>
    </DockPanel>
Run Code Online (Sandbox Code Playgroud)


Met*_*urf 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>
Run Code Online (Sandbox Code Playgroud)