ColumnDefinition.Width的数据类型是:GridLength,所以就可以写为:
column1.Width = new GridLength(1, GridUnitType.Star); //column1为一个实例
如果ColumnDefinition的Width="Auto" 则在C#代码里就可以写为
column1.Width =GridLength.Auto;
这里不要搞混了, GridLength.Auto是一个结构,而 new GridLength(1, GridUnitType.Star);是一个类
下面来一个完整的布局代码,全部使用C#代码完成(练习的)
public
partial
class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 显示网格
grid1.ShowGridLines = true;
// 行
RowDefinition row1 = new RowDefinition();
RowDefinition row2 = new RowDefinition();
// 列
ColumnDefinition column1 = new ColumnDefinition();
ColumnDefinition column2 = new ColumnDefinition();
// 使用*号布局,当值为1的时候,表示* 值为2的时候,表示2* 就是说,第二列的宽度是第一列宽度的2倍
column1.Width = new GridLength( 1, GridUnitType.Star);
column2.Width = new GridLength( 2, GridUnitType.Star);
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
Button button4 = new Button();
// 将行和列添加到Grid面板里
grid1.RowDefinitions.Add(row1);
grid1.RowDefinitions.Add(row2);
grid1.ColumnDefinitions.Add(column1);
grid1.ColumnDefinitions.Add(column2);
// 将按钮添加到Grid面板里
grid1.Children.Add(button1);
grid1.Children.Add(button2);
grid1.Children.Add(button3);
grid1.Children.Add(button4);
button1.Content = " 1 ";
button2.Content = " 2 ";
button3.Content = " 3 ";
button4.Content = " 4 ";
// 设置每个按钮所在的单元格中
Grid.SetRow(button1, 0);
Grid.SetColumn(button1, 0);
Grid.SetRow(button2, 0);
Grid.SetColumn(button2, 1);
Grid.SetRow(button3, 1);
Grid.SetColumn(button3, 0);
Grid.SetRow(button4, 1);
Grid.SetColumn(button4, 1);
}
}
{
public MainWindow()
{
InitializeComponent();
// 显示网格
grid1.ShowGridLines = true;
// 行
RowDefinition row1 = new RowDefinition();
RowDefinition row2 = new RowDefinition();
// 列
ColumnDefinition column1 = new ColumnDefinition();
ColumnDefinition column2 = new ColumnDefinition();
// 使用*号布局,当值为1的时候,表示* 值为2的时候,表示2* 就是说,第二列的宽度是第一列宽度的2倍
column1.Width = new GridLength( 1, GridUnitType.Star);
column2.Width = new GridLength( 2, GridUnitType.Star);
Button button1 = new Button();
Button button2 = new Button();
Button button3 = new Button();
Button button4 = new Button();
// 将行和列添加到Grid面板里
grid1.RowDefinitions.Add(row1);
grid1.RowDefinitions.Add(row2);
grid1.ColumnDefinitions.Add(column1);
grid1.ColumnDefinitions.Add(column2);
// 将按钮添加到Grid面板里
grid1.Children.Add(button1);
grid1.Children.Add(button2);
grid1.Children.Add(button3);
grid1.Children.Add(button4);
button1.Content = " 1 ";
button2.Content = " 2 ";
button3.Content = " 3 ";
button4.Content = " 4 ";
// 设置每个按钮所在的单元格中
Grid.SetRow(button1, 0);
Grid.SetColumn(button1, 0);
Grid.SetRow(button2, 0);
Grid.SetColumn(button2, 1);
Grid.SetRow(button3, 1);
Grid.SetColumn(button3, 0);
Grid.SetRow(button4, 1);
Grid.SetColumn(button4, 1);
}
}