对齐堆栈面板中的项目?

Shi*_*mmy 137 wpf layout alignment wpf-controls stackpanel

我想知道我是否可以在水平导向的StackPanel中有2个控件,以便正确的项目应该停靠在StackPanel的右侧.

我尝试了以下但它不起作用:

<StackPanel Orientation="Horizontal">
    <TextBlock>Left</TextBlock>
    <Button Width="30" HorizontalAlignment="Right">Right<Button>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

在上面的代码片段中,我希望Button停靠在StackPanel的右侧.

注意:我需要使用StackPanel,而不是Grid等.

Dir*_*mar 208

你可以用DockPanel:

<DockPanel Width="300">
    <TextBlock>Left</TextBlock>
    <Button HorizontalAlignment="Right">Right</Button>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)

区别在于a StackPanel会将子元素排列成单行(垂直或水平),而a DockPanel定义一个区域,您可以相对于彼此水平或垂直排列子元素(该Dock属性更改元素相对于其他元素的位置)同一容器中的元素.对齐属性,例如HorizontalAlignment,更改元素相对于其父元素的位置).

更新

正如评论中指出的那样,你也可以使用a的FlowDirection属性StackPanel.请参阅@ D_Bester的答案.

  • Windows 8中没有DockPanel,还有其他解决方案吗? (2认同)

小智 64

呦可以设置FlowDirectionStack panelRightToLeft,然后所有项目将对准右侧.

  • 小心,这使我的文字流向错误的方向! (21认同)
  • 但请注意,这会更改(反转)StackPanel中控件的顺序. (3认同)

mop*_*led 28

对于那些在这个问题谁绊倒,这里是如何做到这一点的布局Grid:

<Grid>
    <TextBlock Text="Server:"/>
    <TextBlock Text="http://127.0.0.1" HorizontalAlignment="Right"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

创建

Server:                                                                   http://127.0.0.1
Run Code Online (Sandbox Code Playgroud)


Ros*_*oss 18

无法按照我想要的方式使用DockPanel工作,并且反转StackPanel的流向是很麻烦的.使用网格不是一个选项,因为它内部的项目可能在运行时隐藏,因此我不知道设计时的列总数.我能想出的最好和最简单的解决方案是:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="1" Orientation="Horizontal">
        <!-- Right aligned controls go here -->
    </StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)

这将导致StackPanel内部的控件与可用空间的右侧对齐,而不管控件的数量 - 无论是在设计还是运行时.好极了!:)


Att*_*tif 5

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <TextBlock Text="Left"  />
    <Button Width="30" Grid.Column="1" >Right</Button>
</Grid>
Run Code Online (Sandbox Code Playgroud)


D_B*_*ter 5

这对我来说非常合适。从右边开始,只需将按钮放在第一位。如果FlowDirection成为问题,只需在其周围添加一个StackPanel并为该部分指定FlowDirection =“ LeftToRight”。或简单地为相关控件指定FlowDirection =“ LeftToRight”。

<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" FlowDirection="RightToLeft">
    <Button Width="40" HorizontalAlignment="Right" Margin="3">Right</Button>
    <TextBlock Margin="5">Left</TextBlock>
    <StackPanel FlowDirection="LeftToRight">
        <my:DatePicker Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
    </StackPanel>
    <my:DatePicker FlowDirection="LeftToRight" Height="24" Name="DatePicker1" Width="113" xmlns:my="http://schemas.microsoft.com/wpf/2008/toolkit" />    
</StackPanel>
Run Code Online (Sandbox Code Playgroud)