为什么带有*的WPF网格中的两列不具有相同的大小?

Ign*_*cia 13 .net wpf grid resize sizetocontent

使用下面的代码我期望以两个ListBox结束,它们具有相同的宽度,因为它们是两个columndefinition,带有With ="*"

而不是这看起来大小是由ListBox上的文本大小确定的,这是没有意义的,因为这个文本比ListBox小得多,因此TextBlock有足够的空间来容纳文本.

<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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

WPF自动调整功能让我发疯...任何想法?谢谢.

编辑:在VS2008中完成的一切,以防万一.

Ale*_* A. 12

看这个:

http://www.wpftutorial.net/GridLayout.html

"明星(*):

占用尽可能多的空间(在填充所有自动和固定大小的列之后),按比例划分所有星形大小的列.所以3*/5*表示与30*/50*相同.请记住,如果网格大小是根据其内容计算的,则星号大小不起作用."

你的代码就是这种情况.我怀疑这也是其他人测试它的原因,如果他们将Grid粘贴到大于TextBlock设置的300像素的窗口中.如果我使用完全相同的XAML,我会遇到同样的问题.

编辑:这就是"为什么".有关可能的替代解决方案,请参阅此问题:Wpf:网格:如何共享列/行高度宽度?

在这种情况下,最近的答案(不是提问者选择的答案)似乎是最有用的答案.


Ign*_*cia 4

亚历克斯. A找到了发生这种情况的确切原因,并且我幸运地找到了解决方案。只需将 * 更改为 0 我就得到了预期的结果(如果你问我的话,我会觉得很奇怪):

<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>
Run Code Online (Sandbox Code Playgroud)