WPF TextBox will not populate StackPanel

I have a TextBox control in a StackPanel that has Orientation set to Horizontal but cannot force 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 here is what it looks like:

alt text

Why doesn't the TextBox populate the StackPanel?

I know that I can have more control using the Grid control, I'm just confused in the layout.

+82
wpf
Sep 17 '10 at 16:16
source share
3 answers

I had the same issue with the StackPanel , and the behavior was "by design." StackPanel designed to "stack" things even outside the visible area, so it will not allow you to fill the remaining space in the size of the stack.

You can use the DockPanel with LastChildFill set to true and combine all the controls that don't fill the content with Left to simulate the desired effect.

 <DockPanel Background="Orange" LastChildFill="True"> <TextBlock Text="a label" Margin="5" DockPanel.Dock="Left" VerticalAlignment="Center"/> <TextBox Height="25" Width="Auto"/> </DockPanel > 
+126
Sep 17 '10 at 16:21
source share

Instead, I recommend using Grid:

 <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"> <Grid Background="Orange"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="a label" VerticalAlignment="Center"/> <TextBox Grid.Column="1"/> </Grid> </Window> 

Another way around this problem is to put the label on top and not right. I noticed that UWP has a built-in header property that you can use for this, but I'm not sure if the header property exists for WPF.

 <TextBox Header="MyLabel" /> 
+11
Feb 12 '18 at 2:05
source share

I can populate the StackPanel with a text box using the following:

 <StackPanel Margin="5,5,5,5"> <Label Content = "lblExample" Width = "70" Padding="0" HorizontalAlignment="Left"/> <TextBox Name = "txtExample" Text = "Example Text" HorizontalContentAlignment="Stretch"/> </StackPanel> 

Textbox Horizontal Fill Panel

0
Jul 11 '19 at 4:06
source share



All Articles