动态行定义高度

时间:2009-07-30 16:30:33

标签: c# wpf grid

我有一个简单的xaml控件,其中包含以下网格行定义:

<Grid.RowDefinitions>
            <RowDefinition Height="15*" />
            <RowDefinition Height="60*" />
            <RowDefinition Height="20*" />
            <RowDefinition Height="20*" />
            <RowDefinition Height="15*" />
</Grid.RowDefinitions>

每行1-3个包含一个文本块,其中可能包含或不包含文本。在后面的代码中,如果没有文本,我想最小化RowDefinition。基本上我的代码背后有以下内容:

if(textblock.Text != ""){
   grid.RowDefinitions[elementRow].Height = new GridLength(20, GridUnitType.Star);
}
else{
   grid.RowDefinitions[elementRow].Height = new GridLength(0, GridUnitType.Star);
}

我希望第0行和第4行保留,因为它们在xaml中定义。不幸的是,即使第2行的文本块中有文本没有显示任何内容,这也不起作用。

我做错了什么。

感谢任何帮助,

詹姆斯

3 个答案:

答案 0 :(得分:9)

不要使用星号表示法,请使用Auto作为RowDefinitions。如果TextBlock.Text为空,请将TextBlock的Visibility设置为Visibility.Collapsed。然后网格行将自动缩小为空。

答案 1 :(得分:9)

这不是你问题的答案,只是一些信息。

高度中的*(或列的宽度)表示行(或列)宽度Height =“*”(或Width =“*”)将占用剩余的空间。因此,如果网格中有4行,Height =“100”,则执行此操作:

<Grid.RowDefinitions>
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="*" />
</Grid.RowDefinitions>

行宽Height =“*”将是70 DIU(设备无关单位)。

在星号(Height =“2 *”)之前添加一个数字只有在使用星号有多行的情况下才有效,星号前面的数字表示该特定行需要多少空间(2 * =两次)同样多,3 * 3倍,等等......)。 I. E.:

<Grid.RowDefinitions>
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="2*" /> <!-- this row will be twice as tall as the one below -->
            <RowDefinition Height="*" />
</Grid.RowDefinitions>

这里第3排的高度为54 DIU(是第4排的两倍,高度约为26 DIU),两个高度总和为80,这是网格的其余部分(10 + 10 + 26 + 54 = 100,网格高度。

顺便说一句,我同意查理的回答。

答案 2 :(得分:0)

您可以将项目放在 UniformGrid 中,其中Columns =“1”并在获得emptry文本时将TextBox Visibility折叠。

 <UniformGrid Columns="1">
    <TextBlock Text="AAAA" Visibility="Collapsed" Grid.Row="0"/>
    <TextBlock Text="BBBBB" Grid.Row="1"/>
    <TextBlock Text="CCCCC" Grid.Row="2"/>
    <TextBlock Text="DDDDD" Grid.Row="3"/>
    <TextBlock Text="EEEE" Grid.Row="4"/>
</UniformGrid>