Edward Tanguay
Edward Tanguay

Reputation: 193302

XAML: why is button on top when I clearly said to go on bottom?

In XAML, I want the button to go on the BOTTOM of the red rectangle.

I clearly say:

"HorizontalAlignment="Right"
VerticalAlignment="Bottom"

It goes to the right but stays on the top. Why is that?

alt text http://tanguay.info/web/external/buttonTop.png

<UserControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MultiplePages.Page"
    Width="300" Height="150">

    <StackPanel HorizontalAlignment="Stretch" 
        VerticalAlignment="Stretch" Width="300" Height="150" Orientation="Vertical">

        <StackPanel Width="300" Height="100" Background="Blue">
            <TextBlock x:Name="theTextBlock" Text="This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. This is page one. " 
            TextWrapping="Wrap" Height="100" Width="300" HorizontalAlignment="Left"/>
        </StackPanel>

        <StackPanel Width="300" Height="50" Background="Red">

            <Button Name="Switch" Content="Switch Page" Width="100" Height="20"
            HorizontalAlignment="Right" 
            VerticalAlignment="Bottom"/>

        </StackPanel>

    </StackPanel>

</UserControl>

Upvotes: 2

Views: 1774

Answers (1)

Steven Robbins
Steven Robbins

Reputation: 26599

The StackPanel is meant to take it's sizing from it's elements and it's container (depending on it's orientation), although what you've done looks correct, that's not the way the StackPanel is "meant" to be used. Although it looks like it's the height it's set, it's actual height (that it uses for laying out child controls) is the size of it's content (the button). The StackPanel has it's uses, but if you are doing anything other than a simple stack of controls then you generally should be using something else.

You can fix it by either sticking a sized grid inside:

<StackPanel Width="300" Height="50" Background="Red">
          <Grid Height="50">
            <Button Name="Switch" Content="Switch Page" Width="100" Height="20"
            HorizontalAlignment="Right" VerticalAlignment="Bottom"
            />
          </Grid>
        </StackPanel>

Or, for that particular layout, you might want to look at DockPanel, which will behave more like you would expect it to.

Upvotes: 3

Related Questions