Search code examples
wpfwpf-controlsstretch

Why doesn't a textbox stretch inside stackpanel WPF?


<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="25*" />
        <ColumnDefinition Width="49*" />
        <ColumnDefinition Width="25*" />
    </Grid.ColumnDefinitions>
    <StackPanel Grid.Column="1" Margin="30" VerticalAlignment="Center">
        <StackPanel Orientation="Horizontal">
            <TextBlock Margin="0,0,5,0" Text="Username:" />
            <TextBox HorizontalAlignment="Stretch"/>
        </StackPanel>
    </StackPanel>

--Result image--

Im trying to make it so that the textbox will fill the rest of the space inside the current StackPanel. however the "Stretch" propety doesn't seem to work - why is that?

Is there a different way do it or what am I doing wrong?


Solution

  • A StackPanel always tries to achieve the minimum possible height/width, depending on orientation; therefore, Stretch has no effect. You might want to use a DockPanel instead, which allows children to stretch:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="25*" />
            <ColumnDefinition Width="49*" />
            <ColumnDefinition Width="25*" />
        </Grid.ColumnDefinitions>
        <StackPanel Grid.Column="1"
                    Margin="30"
                    VerticalAlignment="Center">
            <DockPanel>
                <TextBlock DockPanel.Dock="Left" Margin="0,0,5,0"
                           Text="Username:" />
                <TextBox HorizontalAlignment="Stretch"/>
            </DockPanel>
        </StackPanel>
    </Grid>
    

    enter image description here