WPF TextBox won't fill in StackPanel

后端 未结 4 1408
無奈伤痛
無奈伤痛 2020-11-29 03:55

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

相关标签:
4条回答
  • 2020-11-29 04:20

    I would recommend using a Grid instead:

    <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>
    

    The other way to get around this problem is to stack the label on top instead of to the right. I noticed that UWP has a built in header property you can use for that, not sure if the header property exists for WPF.

    <TextBox Header="MyLabel" />
    
    0 讨论(0)
  • 2020-11-29 04:23

    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 >
    
    0 讨论(0)
  • 2020-11-29 04:26

    Old question by actual topic:

    HorizontalAlignment="Stretch"
    

    is the required thing. Juste be sure that you remove the width.

    0 讨论(0)
  • 2020-11-29 04:29

    I am able to fill a StackPanel with a textbox 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 Horizontally Filling Stackpanel

    0 讨论(0)
提交回复
热议问题