WPF. Auto columns not sizing the right way with ColumnSpan

I'm having trouble with an auto column not sizing the way I wanted it to. I'm using following code:

<Grid>
    <Grid.ColumnDefinitions>
         <ColumnDefinition Width="auto"/>
         <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="10"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <Grid Grid.ColumnSpan="2">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition Width="300"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="User: "/>
        <TextBox Grid.Row="2" Grid.Column="2" />
    </Grid>
    <Button Grid.Row="2" Grid.Column="1" Content="Search"/>
</Grid>

The way I want this to work is that the second auto column takes the width needed for just the button (so that it is aligned right below the grid ) and that the first auto column takes the remaining width needed for the rest of the grid.

However the second column gets longer and the width is divided as if it were * columns. see below screenshot

link to image as I do not have the right rep to post

Is this my misunderstanding of how auto columns work? If so, what is the best workaround to this. Please note that this is simplified code as this is part of a form with more then one column so I'd rather avoid wrapping my objects to much in other grids or stackpanels.

Also setting a width on the button is also out of the question as I want it to be exactly the size needed for the 'Search' content

EDIT: The layout I'm trying to achieve is something like this

Upvotes: 0

Views: 484

Answers (1)

Ravi Patni
Ravi Patni

Reputation: 117

First of all,this can be achieved by only one grid. No need of child grid. You can use this code. For better understanding could you provide a image what you want to achieve.

  <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="auto"/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="10"/>
                <RowDefinition Height="auto"/>
            </Grid.RowDefinitions>
            <TextBlock  Text="User: "/>
            <TextBox  Grid.Column="1" />
            <Button Grid.Row="2" Grid.Column="1" Content="Search" HorizontalAlignment="Right" Width="Auto"/>
        </Grid>

Upvotes: 2

Related Questions