tags:

views:

84

answers:

1

I have a TextBox control within a StackPanel whose Orientation is set to Horizontal, but can't get the TextBox to fill the remaining StackPanel space.

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="180" Width="324">

    <StackPanel Background="Orange" Orientation="Horizontal" >
        <TextBlock Text="a label" Margin="5" VerticalAlignment="Center"/>
        <TextBox Height="25" HorizontalAlignment="Stretch" Width="Auto"/>
    </StackPanel>
</Window>

And this is what it looks like:

alt text

Why is that TextBox not filling the StackPanel?

I know I can have more control by using a Grid control, I'm just confused about the layout.

+7  A: 

I've had the same problem with StackPanel, and the behavior is "by design". StackPanel is meant for "stacking" things even outside the visible region, so it won't allow you to fill remaining space in the stacking dimension.

You can use a DockPanel with LastChildFill set to true and dock all the non-filling controls to the Left to simulate the effect you want.

<DockPanel Background="Orange" LastChildFill="True">
    <TextBlock Text="a label" Margin="5" 
        DockPanel.Dock="Left" VerticalAlignment="Center"/>
    <TextBox Height="25" Width="Auto"/>
</DockPanel >
Zach Johnson
Just to clarify - LastChildFill is by default set to "True" and setting HorizontalAlignment to stretch for the TextBox has no effect. :-)
Goblin
@Goblin: Yes...I copied and pasted the OP's code but forgot to remove `HorizontalAlignment`. :)
Zach Johnson
Seriously, this is by design? Seems weird, since the control itself is obviously spanning the whole width. Are you saying that the content area is not necessarily the same as the visible area?
Henry Jackson
@Henry: Yes. `StackPanel` was created for controls such as `ListBox`. In the `ListBox`, the `StackPanel` does take up all the visible space, but items may go outside the visible region (into scrolling). This behavior is only in the stacking dimension, so child controls can take up all the vertical space if `Orientation="Horizontal"` or vice-versa.
Zach Johnson
@Henry: Here are some related questions: http://stackoverflow.com/questions/569095/wpf-xaml-how-to-get-stackpanels-children-to-fill-maximum-space-downward http://stackoverflow.com/questions/832216/wpf-how-to-make-controls-stretch-in-a-stackpanel
Zach Johnson