gpt4 book ai didi

c# - WPF Grid RowSpan布局理解

转载 作者:太空宇宙 更新时间:2023-11-03 13:21:25 24 4
gpt4 key购买 nike

我有一个非常简单的 XAML

<ui:BorderedGrid>
<ui:BorderedGrid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</ui:BorderedGrid.RowDefinitions>
<ui:BorderedGrid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</ui:BorderedGrid.ColumnDefinitions>
<StackPanel Background="Blue" VerticalAlignment="Top" Grid.Row="0" Grid.Column="0" Margin="5" Width="200" Height="70"></StackPanel>
<StackPanel Background="Red" VerticalAlignment="Top" Grid.Row="1" Grid.Column="0" Margin="5" Grid.RowSpan="2" Width="200" Height="300"></StackPanel>
<StackPanel Background="Plum" VerticalAlignment="Top" Grid.Row="0" Grid.Column="1" Margin="5" Grid.RowSpan="2" Width="200" Height="150"></StackPanel>
<StackPanel Background="SaddleBrown" VerticalAlignment="Top" Grid.Row="2" Grid.Column="1" Margin="5" Width="200" Height="250"></StackPanel>
</ui:BorderedGrid>

BorderedGrid 只是 WPF 标准 Grid 的扩展版本,它重写了 OnRender 函数来绘制列线和行线。下面是它的实现

public class BorderedGrid : Grid
{
protected override void OnRender(DrawingContext dc)
{
double leftOffset = 0;
double topOffset = 0;
System.Windows.Media.Pen pen = new System.Windows.Media.Pen(System.Windows.Media.Brushes.LightGray, 1);
pen.Freeze();

foreach (RowDefinition row in this.RowDefinitions)
{
dc.DrawLine(pen, new System.Windows.Point(0, topOffset), new System.Windows.Point(this.ActualWidth, topOffset));
topOffset += row.ActualHeight;
}
// draw last line at the bottom
dc.DrawLine(pen, new System.Windows.Point(0, topOffset), new System.Windows.Point(this.ActualWidth, topOffset));

foreach (ColumnDefinition column in this.ColumnDefinitions)
{
dc.DrawLine(pen, new System.Windows.Point(leftOffset, 0), new System.Windows.Point(leftOffset, this.ActualHeight));
leftOffset += column.ActualWidth;
}
// draw last line on the right
dc.DrawLine(pen, new System.Windows.Point(leftOffset, 0), new System.Windows.Point(leftOffset, this.ActualHeight));

base.OnRender(dc);
}
}

问题是,我假设输出应该是这样的

Output should be like this

但实际输出是这样的

enter image description here

我的问题是为什么第一行留下这个空白?我想我错过了非常简单的事情.. :(

最佳答案

无论列如何,所有行都需要对齐。由于第 0 行的高度是自动的。它的实际高度成为其最高子元素的高度 + 边距,这将是梅花高度的一部分 + 10(从边距开始)。

由于蓝色面板的高度 (70) 比其所在行(第 0 行)的高度短,并且它与顶部垂直对齐,因此您可以看到它下方的空白区域。

我相信您看到的结果是基于行、行跨度、高度等配置的预期结果。

在某种程度上,您的水平网格线已经暗示了计算出的行高。

这是另一种看待它的方式:

第 2 行的高度是 SaddleBrown 的高度

第一行的高度是第二行的高度减去红色的高度

第 0 行的高度是 Plum 的高度减去第 1 行的高度

第 0 行的高度大于 Blue 的高度。蓝色与顶部垂直对齐,因此下方有一个空白区域。

关于c# - WPF Grid RowSpan布局理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24038485/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com