Blair Davidson
Blair Davidson

Reputation: 951

wpf grid and stackpanel fill

I have a grid with 2 rows one for a name and button and the other for output.

I want the first row to stretch the full width and the button to align to the right.

Wondering what I am missing as I thought the stackpanel would fill the width.

<Window x:Class="Sample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

        <StackPanel Orientation="Horizontal" Grid.Row="0" Grid.Column="0" >
            <TextBox Name="NameTextBox" MinWidth="150" HorizontalAlignment="Stretch"/>
            <Button Margin="10,0" Name="AlertButton" Content="Say Hello" HorizontalAlignment="Stretch" />
        </StackPanel>

        <TextBox  Name="OutpuTextBox" MinLines="5" Grid.Row="1" Grid.Column="0"/>
    </Grid>
</Window>

Upvotes: 0

Views: 3342

Answers (1)

dkozl
dkozl

Reputation: 33394

Horizontal StackPanel ignores horizontally alignment of its children. You can change your layout to 2 columns and put Button in the second column of first row and set bottom TextBox to span across 2 columns

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <TextBox Name="NameTextBox" MinWidth="150" HorizontalAlignment="Stretch"/>
    <Button Margin="10,0" Name="AlertButton" Content="Say Hello" HorizontalAlignment="Stretch" Grid.Column="1" />
    <TextBox  Name="OutpuTextBox" MinLines="5" Grid.Row="1" Grid.ColumnSpan="2"/>
</Grid>

Upvotes: 1

Related Questions