WPF窗口采用默认的Grid布局控件,其“Name”值为“grid1”,在“grid1”中添加三个Button按钮。动态添加控件并访问这些控件的代码如下:
1 private void button1_Click_1(object sender, RoutedEventArgs e) 2 { 3 //添加第一个文本框 4 TextBox tb1 = new TextBox(); 5 tb1.Name = "myTextBox1"; 6 7 tb1.Text = "第一个文本框"; 8 tb1.Width = 100; 9 tb1.Height = 30; 10 11 tb1.HorizontalAlignment = HorizontalAlignment.Left; 12 tb1.VerticalAlignment = VerticalAlignment.Top; 13 tb1.Margin = new Thickness(100, 100, 0, 0); 14 15 grid1.Children.Add(tb1); 16 17 //添加第二个文本框 18 TextBox tb2 = new TextBox(); 19 tb2.Name = "myTextBox2"; 20 21 tb2.Text = "第二个文本框"; 22 tb2.Width = 100; 23 tb2.Height = 30; 24 25 tb2.HorizontalAlignment = HorizontalAlignment.Left; 26 tb2.VerticalAlignment = VerticalAlignment.Top; 27 tb2.Margin = new Thickness(100, 150, 0, 0); 28 29 grid1.Children.Add(tb2); 30 31 } 32 33 private void button2_Click(object sender, RoutedEventArgs e) 34 { 35 //访问添加的全部文本框 36 foreach(var c in grid1.Children) 37 { 38 if (c is TextBox) 39 { 40 TextBox tb = (TextBox)c; 41 MessageBox.Show(tb.Text); 42 } 43 } 44 45 } 46 47 private void button3_Click(object sender, RoutedEventArgs e) 48 { 49 //访问添加的某个文本框 50 foreach (var c in grid1.Children) 51 { 52 if (c is TextBox) 53 { 54 TextBox tb = (TextBox)c; 55 if (tb.Name == "myTextBox2") 56 { 57 MessageBox.Show(tb.Text); 58 } 59 } 60 } 61 }