James Ko
James Ko

Reputation: 34499

Preventing StackPanel items from overlapping

I am designing a Windows Phone application and I would like to stack a TextBlock and a Button next to each other horizontally. This is my pseudo-code on what I would like to achieve:

<StackPanel Name="titlePanel" Orientation="Horizontal" Margin="0,-6.5,0,26.5">
    <TextBlock Name="titleBox" Text="{Binding Title}" Style="{ThemeResource HeaderTextBlockStyle}" CharacterSpacing="{ThemeResource PivotHeaderItemCharacterSpacing}"/>
    <Button Content="press" Width="whatever space is left" Length="what the width is"/> <!--how do I do this?-->
</StackPanel>

I got an error when I tried to put Width="*", so I'm looking to do something like Width="titlePanel.Width - titleBox.Width" and Length="this.Width", only I can't seem to be able to reference other objects inside XAML. I don't want to put into the code-behind file to format the size of the Button every time that page comes up... how would this be achieved?

Upvotes: 1

Views: 3800

Answers (2)

grube
grube

Reputation: 48

You can't do it with StackPanel because, the stack panel measures every child element with positive infinity as the constraint for the axis that it is stacking elements along. The child controls have to return how big they want to be (positive infinity is not a valid return from the MeasureOverride in either axis) so they return the smallest size where everything will fit. They have no way of knowing how much space they really have to fill.

So you should use grid to achieve desired behavior.

Upvotes: 1

Frebin Francis
Frebin Francis

Reputation: 1915

You can use grid control for this kind of purpose

try this one

<Grid HorizontalAlignment="Stretch">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <TextBlock Name="titleBox" Grid.Column="0" Margin="5,0" HorizontalAlignment="Stretch" TextWrapping="Wrap" Text="Your text goes here." />
        <Button Content="press" Grid.Column="1" Margin="5,0" HorizontalAlignment="Stretch"/>

    </Grid>

Hope this helps.

Upvotes: 0

Related Questions