我正在尝试创建一个自定义网格,根据最大的可用子维度和窗口维度,它可以动态调整大小并重新定位它的子项。这意味着我必须动态地重绘我的行和列定义。下面给出的是我的自定义网格代码
public class GridPanel : Grid
{
#region Fields
Size maxItemSize;
int maxPossibleColumns = 0;
int maxPossibleRows = 0;
#endregion
#region Overrides
protected override Size MeasureOverride(Size constraint)
{
this.ShowGridLines = true;
GetMaxItemSize(constraint);
//SetupGridCells(constraint);
return constraint;
}
protected override Size ArrangeOverride(Size arrangeSize)
{
//SetupGridCells(arrangeSize);
return base.ArrangeOverride(arrangeSize); //Caught a nullReferrence exception
}
#endregion
#region Methods
private void GetMaxItemSize(Size availableSize)
{
foreach (UIElement item in Children)
{
item.Measure(availableSize);
maxItemSize = item.DesiredSize.Width > maxItemSize.Width ? item.DesiredSize : maxItemSize;
}
}
private void SetupGridCells(Size finalSize)
{
ColumnDefinition spaceWidth;
ColumnDefinition cellWidth;
RowDefinition spaceHeight;
RowDefinition cellHeight;
maxPossibleColumns = (int)(finalSize.Width / maxItemSize.Width);
for (int i = 0; i < maxPossibleColumns; i++)
{
spaceWidth = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
cellWidth = new ColumnDefinition { Width = new GridLength(maxItemSize.Width) };
this.ColumnDefinitions.Add(spaceWidth);//***
this.ColumnDefinitions.Add(cellWidth);//***
}
spaceWidth = new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) };
this.ColumnDefinitions.Add(spaceWidth);//***
/////////////////////////////////////////////////////////////////////////////////////////////
maxPossibleRows = (int)(finalSize.Height / maxItemSize.Height);
for (int i = 0; i < maxPossibleRows; i++)
{
spaceHeight = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
cellHeight = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
this.RowDefinitions.Add(spaceHeight);//***
this.RowDefinitions.Add(cellHeight);//***
}
spaceHeight = new RowDefinition { Height = new GridLength(1, GridUnitType.Star) };
this.RowDefinitions.Add(spaceHeight);
}
#endregion
}
这就是我使用面板的方式
<Panels:GridPanel>
<Rectangle Height="10" Width="10" Fill="Red" />
<Rectangle Height="20" Width="20" Fill="Black" />
<Rectangle Height="30" Width="30" Fill="Green" />
<Rectangle Height="40" Width="40" Fill="Blue" />
<Rectangle Height="50" Width="50" Fill="Aqua" />
<Rectangle Height="60" Width="60" Fill="Wheat" />
<Rectangle Height="70" Width="70" Fill="Blue" />
<Rectangle Height="80" Width="80" Fill="DarkBlue" />
<Rectangle Height="90" Width="90" Fill="DarkGoldenrod" />
<Rectangle Height="100" Width="100" Fill="Gainsboro" />
<Rectangle Height="110" Width="110" Fill="Pink" />
<Rectangle Height="120" Width="120" Fill="Brown" />
</Panels:GridPanel>
SetupGridCells()是我正在尝试重绘行和列的方法。问题是即使我在ArrangeOveride()或MeasureOverride()中调用此方法,它也会在返回base.ArrangeOverride(arrangeSize)中抛出nullReference异常;在进一步调试时,我注意到this.ColumnDefinitions.Add(spaceWidth); // *(那些用注释// * 标记的行)导致了这个问题。
有人可以指出问题是什么吗?提前致谢