开发者

WPF How do I align buttons on the right with x number of buttons

I am trying to align buttons on the right of a dockpanel, but I hide and show buttons based on a certian criteria. I am in need of howto right justify based on what is shown. Currently I am using this:

    <DockPanel HorizontalAlignment="Stretch" Height="34" Margin="0,0,2,35" VerticalAlignment="Bottom">
        <Button DockPanel.Dock="Right" Height="23" x:Name="btnOne" Click="btnOne_Click" Margin="0,0,5,5" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="Auto">
            <TextBlock x:Name="txtBtnOneText" />
        </Button>
        <Button DockPanel.Dock="Right" Height="23" Width="Auto" x:Name="btnTwo" Visibility="Hidden" Click="btnTwo_Click" HorizontalAlignment="Right" Margin="0,0,5,5" VerticalAlignment="Bottom">
            <TextBlock x:Name="txtBtnTwoText" />
        </Button>
    </DockPanel>

When I only show button btnOne then I want it to be right justified, when I only show btnTwo then I want it to be开发者_运维百科 right justified, or when I show both of them then I would like btnOne on the farmost right and btnTwo to be 5px to the left of btnOne.

Thanks!


Instead of dockpanel try using stackpanel like this -

        <StackPanel Grid.Row="0" Orientation="Horizontal">
            <Button x:Name="btn1" Content="btn1" Height="34" />
            <Button x:Name="btn2" Margin="5,0,0,0" Content="btn2" Height="34" />
        </StackPanel>

And just set the visibility of the button to collapsed instead of hidden when you want one button to hide and it won't take the space reserved for it. Whereas if you set the visibility to hidden it wont be shown on the UI but it will still take the space reserved for it.


So what are you having trouble with? I would do this using a simple StackPanel:

<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
    <Button>One</Button>
    <Button Margin="3 0 0 0">Two</Button>
</StackPanel>


For me it worked way better with Grids instead of StackPanel

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*" />
        <ColumnDefinition Width="32" />
    </Grid.ColumnDefinitions>
    <TextBlock Name="TextBlock" Grid.Column="0" Text="This is a text block" B TextAlignment="Center" />
    <Button x:Name="CloseButton" Grid.Column="1" FontSize="12" Content="X" Click="CloseButton_Click" />
</Grid>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜