我在后面的代码中将行添加到网格中,但每次末尾的一些行都会显示在彼此的顶部(重叠;就好像它们位于同一行中一样)。我知道我设置的行号不相同,并且每行的高度为 auto。
网格没有固定高度,但位于固定高度的选项卡标题内。我使用带有网格的滚动条,效果很好(当我添加更多项目时它会扩展),但末尾总是有一些重叠的行。所以网格并不只接受固定的数字或保持固定的长度。即使我添加几行,并且网格只占据屏幕的一半,最后几行最终也会重叠。
我尝试对网格做的任何事情似乎都没有改变任何东西 - 我尝试将高度设置为自动,固定高度,一切都是一样的。我真的很困惑到底发生了什么。
如有任何建议,我们将不胜感激。我知道 DataGrid 在这里可能会更好,但现在我需要坚持使用这个网格。
这是我的xaml代码:
<TabControl Grid.ColumnSpan="5" Grid.RowSpan="15" Height="640">
<TabItem>
<TabItem.Header>
<StackPanel Orientation="Horizontal" Height="23" VerticalAlignment="Center">
<Image Source= "image.png" Margin="0,-3,0,0" VerticalAlignment="Center" Height="17" />
<TextBlock Margin="5,0,0,0" VerticalAlignment="Center">text</TextBlock>
</StackPanel>
</TabItem.Header>
<ScrollViewer VerticalScrollBarVisibility="Auto">
<Grid Name="myGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="350"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="5"/>
<RowDefinition Height="1"/>
<RowDefinition Height="20"/>
<RowDefinition Height="10"/>
</Grid.RowDefinitions>
</Grid>
</ScrollViewer>
</TabItem/
...
在后面的代码中,我以这种方式添加行(到现有的行中):
RowDefinition rowNew1 = new RowDefinition();
rowNew1.Height = new GridLength(1, GridUnitType.Auto);
myGrid.RowDefinitions.Add(rowNew1);
TextBlock tb = new TextBlock();
tb.Text = some_string;
myGrid.Children.Add(tb);
tb.Margin = new Thickness(10, 0, 0, 0);
Grid.SetRow(tb, some_number);
对我来说效果很好。确保您设置的行号实际上是正确的索引:
Grid.SetRow(tb, myGrid.RowDefinitions.IndexOf(rowNew1));
我遇到了同样的问题,我有正确的行号和列号索引。 对我来说,问题是没有向网格中添加足够的行。 我们需要添加整个网格所需的所有行,包括标题。就我而言,我错过了添加标题行,但在循环中添加了数据行。
RowDefinition row= new RowDefinition();
ResultsGrid.RowDefinitions.Add(row);
//ResultsGrid is the custom name of the Grid control
再添加一行解决了我的问题。希望这对某人有帮助。