WPF Grid 用 C# 代码后台设置
运行环境:Window7 64bit,.NetFramework4.61,C# 6.0; 编者:乌龙哈里 2017-02-21
参考:
章节:
- 动态增加行列及控件放置
- 设置Grid的行列尺寸
正文:
一、动态增加行列及控件放置
要用到
Grid.SetRow(控件名, 行序号)
Grid.SetColumn(控件名, 列序号),
另一种写法是:
控件实例.SetValue(Grid.RowProperty, 行序号)
控件实例.SetValue(Grid.ColumnProperty, 列序号)
示例1演示如何增减行和放置控件:
示例1:
public partial class MainWindow : Window
{
private int rowCount = 0;
private int colCount = 0;
private int itemCount = 0;
public MainWindow()
{
InitializeComponent();
grdShow.ColumnDefinitions.Add(new ColumnDefinition());
grdShow.ColumnDefinitions.Add(new ColumnDefinition());
grdShow.ColumnDefinitions.Add(new ColumnDefinition());
grdShow.RowDefinitions.Add(new RowDefinition());
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
itemCount++;
TextBlock tbk = new TextBlock() { Text = $"Item {itemCount.ToString()}" };
if (colCount % 3 == 0)
{
grdShow.RowDefinitions.Add(new RowDefinition());
colCount = 0;
rowCount++;
}
tbk.SetValue(Grid.RowProperty, rowCount);
tbk.SetValue(Grid.ColumnProperty, colCount++);
//Grid.SetRow(tbk, rowCount);
//Grid.SetColumn(tbk, colCount++);
grdShow.Children.Add(tbk);
}
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
itemCount = grdShow.Children.Count;
if (itemCount > 0)
{
grdShow.Children.RemoveRange((itemCount-1) / 3 *3,(itemCount-1) %3 +1);
grdShow.RowDefinitions.RemoveAt((itemCount-1) / 3);
}
}
}
结果如下图:
二、设置Grid的行列尺寸
设置 Grid 行列的尺寸要用到 GridLength 结构。以下示例是设置3行,第1行是固定高度24,第2行是动态高度 1*,第3行也是动态高度 2*,我这里所谓的动态高度是指随着窗口尺寸的变化而变化的尺寸。
示例3:
grdShow.RowDefinitions.Add(new RowDefinition { Height = new GridLength(24)} );
grdShow.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
grdShow.RowDefinitions.Add(new RowDefinition {Height=new GridLength(2,GridUnitType.Star)});
Button btn1 = new Button {Content="Fix",Margin=new Thickness(2)};
Grid.SetRow(btn1, 0);
Button btn2 = new Button {Content="1*", Margin = new Thickness(2) };
Grid.SetRow(btn2, 1);
Button btn3 = new Button {Content="2*", Margin = new Thickness(2) };
Grid.SetRow(btn3, 2);
grdShow.Children.Add(btn1);
grdShow.Children.Add(btn2);
grdShow.Children.Add(btn3);
运行结果如下图,第2行的 Button 是第3行的 Button 高度的1/2,而且随着窗口变化而变化。