Search code examples
.netwpfgridresizesizetocontent

Why two columns in a WPF Grid with * do not have the same size?


with the following code I expected to end with two ListBox with the same Width as they are into two columndefinition with With="*"

Instead of this looks like the size is determined from the size of the text up the ListBox which does not make sense as this text is much smaller than the ListBox and thus the TextBlock has enough space to accommodate the text.

<Window x:Class="UnderstandSizing.Window5"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window5" 
SizeToContent="WidthAndHeight"
ResizeMode="NoResize" >

<Grid>  
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBlock Text="Text1longer" Grid.Row="0" Grid.Column="0" x:Name="Test1" />
    <TextBlock Text="Text1" Grid.Row="0" Grid.Column="2" />
    <ListBox Grid.Row="1" Grid.Column="0" Height="150" />

    <ListBox Grid.Row="1" Grid.Column="2" Height="150" />
    <TextBlock Grid.Row="2" Grid.ColumnSpan="3"  Text="This textblock sets the max width" Width="300" />
</Grid>
</Window>

enter image description here

The WPF automatic sizing feature is driving me mad ... any ideas? Thanks.

EDIT: Everything done in VS2008, just in case it matters.


Solution

  • Alex. A found the exact cause of what is happening and I found a solution in a lucky strike. Just changing the * for 0 I get the expected result (weird if you ask me):

    <Window x:Class="UnderstandSizing.Window5"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window5" 
    SizeToContent="WidthAndHeight"
    ResizeMode="NoResize" >
    
    <Grid>  
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="0" />
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="0" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    
    <TextBlock Text="Text1longer" Grid.Row="0" Grid.Column="0" x:Name="Test1" />
    <TextBlock Text="Text1" Grid.Row="0" Grid.Column="2" />
    <ListBox Grid.Row="1" Grid.Column="0" Height="150" />
    
    <ListBox Grid.Row="1" Grid.Column="2" Height="150" />
    <TextBlock Grid.Row="2" Grid.ColumnSpan="3"  Text="This textblock sets the max width" Width="300" />
    </Grid>
    </Window>