Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

wpf

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!

like image 959
Andrew Sehr Avatar asked Nov 14 '25 14:11

Andrew Sehr


1 Answers

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.

like image 64
Rohit Vats Avatar answered Nov 17 '25 10:11

Rohit Vats



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!