I was wondering if I can have 2 controls in a horizontal-oriented StackPanel so that the right item should be docked to the right side of the StackPanel.
I tried the following but it didn't work:
<StackPanel Orientation="Horizontal">
<TextBlock>Left</TextBlock>
<Button Width="30" HorizontalAlignment="Right">Right<Button>
</StackPanel>
In the snippet above I want the Button to be docked to the right side of the StackPanel.
Note: I need it to be done with StackPanel, not Grid etc.
Yo can set
FlowDirection
ofStack panel
toRightToLeft
, and then all items will be aligned to the right side.Could not get this working using a DockPanel quite the way I wanted and reversing the flow direction of a StackPanel is troublesome. Using a grid is not an option as items inside of it may be hidden at runtime and thus I do not know the total number of columns at design time. The best and simplest solution I could come up with is:
This will result in controls inside of the StackPanel being aligned to the right side of the available space regardless of the number of controls - both at design and runtime. Yay! :)
You can achieve this with a
DockPanel
:The difference is that a
StackPanel
will arrange child elements into single line (either vertical or horizontally) whereas aDockPanel
defines an area where you can arrange child elements either horizontally or vertically, relative to each other (theDock
property changes the position of an element relative to other elements within the same container. Alignment properties, such asHorizontalAlignment
, change the position of an element relative to its parent element).Update
As pointed out in the comments you can also use the
FlowDirection
property of aStackPanel
. See @D_Bester's answer.