Reputation: 83356
I'm trying to get a horizontal StackPanel with some text, and then a button stuck all the way to the right hand side. I tried this:
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,0,0">Ahoy!</TextBlock>
<Button HorizontalAlignment="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
</StackPanel>
Which doesn't seem to work. Obviously adding a margin to the TextBlock will work, like this:
<StackPanel Orientation="Horizontal">
<TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,120,0">Ahoy!</TextBlock>
<Button HorizontalAlignment="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
</StackPanel>
But that's bad for all sorts of reasons. Are there any more natural ways to do this?
Upvotes: 7
Views: 2208
Reputation: 564481
Personally, I would use a Grid instead of a StackPanel for this. Just add two columns, one set to size "*" and one to "Auto", and put your TextBlock in column one, Button in Column two:
Upvotes: 8
Reputation: 38179
StackPanels are OK for simplistic scenarios, as soon as you want full control on the layout, use Grid
Upvotes: 2
Reputation: 24453
Use a DockPanel instead:
<DockPanel>
<TextBlock VerticalAlignment="Center" FontSize="14" Margin="5,0,0,0">Ahoy!</TextBlock>
<Button DockPanel.Dock="Right" Width="25" Height="25" Style="{StaticResource buttonGlassOrb}" Background="Red" />
</DockPanel>
The default Dock setting is Left so it behaves like a Horizontal StackPanel for items that have no explicit Dock setting.
Upvotes: 3