stema
stema

Reputation: 93036

TextBox should occupy available space and not grow when filled with text

I do have a Grid with two columns and two rows. In the first column, first row I do have this:

<StackPanel  Orientation="Vertical" HorizontalAlignment="Stretch" Grid.ColumnSpan="1" Grid.Row="0" Grid.Column="0">
    <StackPanel  Orientation="Horizontal" Height="25" HorizontalAlignment="Stretch">
        <Label Content="Text:"/>
        <TextBox Name="TB_Text" HorizontalAlignment="Stretch" MinWidth="120" />
        <Button Name="BT_TextApply" Content="Apply" Width="75" HorizontalAlignment="Right" Click="BT_TextApply_Click" />
    </StackPanel>
</StackPanel>

I have "rows" (Horizontal StackPanels within a Vertical StackPanel) consisting of a Label, a Textbox and a button that belongs together.

The StackPanels got the attribute HorizontalAlignment="Stretch" so that they use the complete space within their Grid cell, this is OK.

But now I want my three elements also to fill the complete available space of the StackPanel, but I don't get it to work.

Current behaviour

Wanted behaviour

Is there something like a "max" attribute for my TextBox dependend on the size of the StackPanel?

Upvotes: 1

Views: 1080

Answers (2)

stema
stema

Reputation: 93036

For completeness here is the solution I came up with using Josh's answer:

<StackPanel  Orientation="Vertical" HorizontalAlignment="Stretch" Grid.ColumnSpan="1" Grid.Row="0" Grid.Column="0">
    <DockPanel  Height="25" HorizontalAlignment="Stretch" LastChildFill="True">
        <Label Content="Text:" DockPanel.Dock="Left"/>
        <Button Name="BT_TextApply" Content="Apply" Width="75" DockPanel.Dock="Right" Click="BT_TextApply_Click" />
        <TextBox Name="TB_Text"/>
    </DockPanel>
</StackPanel>

The important parts are: The DockPanel needs the attribute LastChildFill="True", then list the items in the DockPanel that should "dock" somewhere and tell them to dock DockPanel.Dock="Left" and DockPanel.Dock="Right" and as last item, place that one that should occupy the remaining space. (The attribute HorizontalAlignment="Stretch" seems not to be needed for the last element, I can't see a difference if its there or not.)

Upvotes: 0

Josh
Josh

Reputation: 2975

Thanks stema. I didn't have the time to try it so I wasn't sure if that would work or not.

Instead of a StackPanel, have you tried using a DockPanel with last child fill set to true? If you dock the label left and the button right. Then ensure the textbox is the last child element of the dockpanel, I would think the size of the textbox would fill the remaining space if its HorizontalAlignment is set to stretch.

Upvotes: 4

Related Questions