WPF:为什么按钮停留在左侧?

时间:2015-08-30 10:41:46

标签: wpf button alignment stackpanel

我在StackPanel中有这个WPF按钮:

<StackPanel Grid.ColumnSpan="6" Grid.Row="12" Orientation="Horizontal" HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="LightGray" Height="40">
            <Button x:Name="btnSave" Click="btnSave_Click" Content="{x:Static res:Strings.ToolPanelEditView_Button_Save}" HorizontalAlignment="Right" />
</StackPanel>

出于某种原因,虽然我将HorizontalAlignment设置为Right,但按钮显示在左侧:

enter image description here

如何让我的保存按钮显示在右侧?

P.S。当我将StackPanel的HorizontalAlignment更改为Right而不是Stretch时,按钮确实显示在右边(就像它应该的那样)(但是StackPanel的灰色背景也不会延伸......

2 个答案:

答案 0 :(得分:0)

我认为Grid更适合您的情况

 <Grid  HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="LightGray" Height="40">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <Button x:Name="btnSave" Grid.Column="1" Content="Save"  HorizontalAlignment="Right"  />
        <!--Your Other Button Grid.Column="2"-->
    </Grid>

或者您也可以使用DockPanel

替换stackPanel

答案 1 :(得分:0)

您可以使用DockPanel作为容器,将其拉伸并将按钮停靠在右侧

    <DockPanel Grid.ColumnSpan="6" Grid.Row="12" HorizontalAlignment="Stretch" VerticalAlignment="Center" Background="LightGray" Height="40">
      <Button Content="Save" DockPanel.Dock="Right"/>
      <Button Content="Cancel" DockPanel.Dock="Right"/>
    </DockPanel>