动态行定义高度

Jam*_*mes 2 c# wpf grid

我有一个简单的xaml控件,具有以下网格行定义:

<Grid.RowDefinitions>
            <RowDefinition Height="15*" />
            <RowDefinition Height="60*" />
            <RowDefinition Height="20*" />
            <RowDefinition Height="20*" />
            <RowDefinition Height="15*" />
</Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)

每行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);
}
Run Code Online (Sandbox Code Playgroud)

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

难道我做错了什么.

任何帮助表示赞赏,

詹姆士

Cha*_*lie 9

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


Car*_*rlo 9

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

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

<Grid.RowDefinitions>
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="10" />
            <RowDefinition Height="*" />
</Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)

行宽Height ="*"将是70 DIU(设备无关单位).

在星号(Height ="2*")之前添加一个数字只有在使用星号有多个行时才有效,星号前面的数字表示该特定行占用的空间多少(2*=两倍, 3*三倍,等等...).IE:

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

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

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