Search code examples
c#wpftextboxgridstackpanel

WPF control extra pixels source


I have these simple wpf controls in this layout. My question where is the extra pixels coming from in the TextBox. It looks like the TextBox is not respecting the Width='Auto' property.

I'm looking to make the Grid Column 0 width equal exactly to the width of the TextBox.

image of rendered code

 <Grid ShowGridLines="True">
 <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <StackPanel>
            <TextBox Text="This TextBox located in Row 0 Column 0"
                     Width="Auto"></TextBox>
        </StackPanel>
        <TextBox Grid.Row="1"
                 Text="This TextBox located in Row 1 Column 0 with Column Span of 2"
                 Grid.ColumnSpan="2"></TextBox>
    </Grid> 

Solution

  • WPF's layout rules can be confusing at times, can't they? :)

    The issue here is that you've set the width to Auto for both columns. Grid is only going to reduce the column width if it needs to or has a good reason to. Since you used Auto for the second column also, and since that column doesn't need to be increased in size to fit the longer second-row text, you get the sizes you see.

    If you really want that first column to be as small as possible, set the second column width to * instead of Auto. (Or just omit the Width attribute…* is the default.)