使用RowSpan时WPF网格自动高度和固定高度意外行为

时间:2016-01-20 10:59:53

标签: wpf grid

我有一些理解问题。我在WPF中有一个Grid,具有交替的固定行高和自动行高。

如果我在第一列中为自动高度的行添加Label,那么这就像我预期的那样。

但是,如果我在第1列中添加一个带有RowSpan的控件,则不是调整了自动高度的行,而是调整了具有固定高度的行。

看一下这个例子:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="5" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" />

    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="150" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>



    <Label Grid.Row="1"
           Grid.Column="0"
           Content="Label1" />

    <Label Grid.Row="3"
           Grid.Column="0"
           Content="Label2" />
    <Label Grid.Row="5"
           Grid.Column="0"
           Content="Label3" />
    <Label Grid.Row="7"
           Grid.Column="0"
           Content="Label4" />

     <Border Grid.Row="1"
            Grid.RowSpan="7"
            Grid.Column="1"
            Height="300"
            Background="Red" />


    <!--<Label Grid.Row="2"
           Grid.Column="0"
           Content="Hallo" />-->

</Grid>

如果我在固定标签上添加标签也不合逻辑我看不到这个标签,因为尺寸5很小。虽然行显示得更大。

1 个答案:

答案 0 :(得分:2)

我认为这是非常有趣的行为。如果您将查看GridLines源代码,您将看到构造函数:

public GridLength(double pixels)
        : this(pixels, GridUnitType.Pixel)
    {
    }

这意味着默认情况下,RowDefenition中的高度具有第二个参数Pixel。 这就是WPF在您的情况下调整网格大小的原因。

有几种方法可以解决它:

  1. 如果你想削减你的控制,你应该将MaxHeight属性添加到Grid的RowDefenitions:

        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
    
  2. 如果您不想控制您的控件,则应添加另一行,其中Height =“*”:

        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="5" MaxHeight="5"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" MaxHeight="5"/>
    
  3. 并为您的行添加控件:

            <Border Grid.Row="1"
            Grid.RowSpan="8"
            Grid.Column="1"
            Height="300"
            Background="Red" />