Warm tip: This article is reproduced from serverfault.com, please click

Out of range when adding a child with a span to a Grid Element in C#

发布于 2020-11-28 03:33:28

I have this code. All grid elements are working except for the very first row with the Grid.Add where I am trying to do a span.

var grid = new Grid();
grid.ColumnSpacing = 4;
grid.RowSpacing = 8;
grid.Margin = 20;
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });

grid.Children.Add(new BaseButton("A", "A"), 0, 2, 0, 0);
grid.Children.Add(new BaseButton("B", "B"), 0, 1);
grid.Children.Add(new BaseButton("C", "C"), 1, 1);
grid.Children.Add(new BaseButton("D", "D"), 0, 2);
grid.Children.Add(new BaseButton("E", "E"), 1, 2);
grid.Children.Add(new BaseButton("F", "F"), 0, 3);
grid.Children.Add(new BaseButton("G", "G"), 1, 3);
grid.Children.Add(new BaseButton("H", "H"), 2, 3);

This row:

grid.Children.Add(new BaseButton("A", "A"), 0, 2, 0, 0);

gives me an error saying:

System.ArgumentOutOfRangeException has been thrown. Specified argument was out of the range of valid values.

Parameter name: bottom

Here's what I need to achieve:

enter image description here

Can anyone review what I have and comment on what might be wrong?

Questioner
Alan2
Viewed
11
Jason 2020-11-28 12:19:07

from the docs

  • right - The right edge of the column span. Must be greater than left. The view won't occupy this column, but will stop just before it.
  • bottom - The bottom edge of the row span. Must be greater than top.

this is somewhat non-intuitive - the right and bottom arguments need to be 1 greater than you would expect them to be.