在事件中执行如下代码:
Grid grid = new Grid();
RowDefinition row1 = new RowDefinition();
RowDefinition row2 = new RowDefinition();
row2.Height = new GridLength(100); //如果不指定高度,默认是最大。
grid.RowDefinitions.Add(row2);
grid.RowDefinitions.Add(row1);
TextBlock block = new TextBlock();
block.Text = "测试文本";
block.SetValue(Grid.RowProperty, 0);
grid.Children.Add(block);
其中:
设置控件在Grid中所占行列还有一种写法:
TextBox text = new TextBox();
grid.Children.Add(text);
Grid.SetRow(text,1);
Grid.SetColumn(text,1);
//同理也可设置TextBox在Grid中占用的列数或行数:
Grid.SetRowSpan(text,1);
Grid.SetColumnSpan(text,1);