//WPF窗口采用默认的Grid布局控件,其“Name”值为“grid1”,在“grid1”中添加三个Button按钮。动态添加控件并访问这些控件的代码如下:
private void button1_Click_1(object sender, RoutedEventArgs e)
{
//添加第一个文本框
TextBox tb1 = new TextBox();
tb1.Name = "myTextBox1";
tb1.Text = "第一个文本框";
tb1.Width = 100;
tb1.Height = 50;
tb1.HorizontalAlignment = HorizontalAlignment.Left;
tb1.VerticalAlignment = VerticalAlignment.Top;
tb1.Margin = new Thickness(100, 100, 0, 0);
grid1.Children.Add(tb1);
//添加第二个文本框
TextBox tb2 = new TextBox();
tb2.Name = "myTextBox2";
tb2.Text = "第二个文本框";
tb2.Width = 100;
tb2.Height = 50;
tb2.HorizontalAlignment = HorizontalAlignment.Left;
tb2.VerticalAlignment = VerticalAlignment.Top;
tb2.Margin = new Thickness(100, 150, 0, 0);
grid1.Children.Add(tb2);
}
private void button2_Click(object sender, RoutedEventArgs e)
{
//访问添加的全部文本框
foreach (var c in grid1.Children)
{
if (c is TextBox)
{
TextBox tb = (TextBox)c;
MessageBox.Show(tb.Text);
}
}
}
private void button3_Click(object sender, RoutedEventArgs e)
{
//访问添加的某个文本框
foreach (var c in grid1.Children)
{
if (c is TextBox)
{
TextBox tb = (TextBox)c;
if (tb.Name == "myTextBox2")
{
MessageBox.Show(tb.Text);
}
}
}
}