在WPF中动态添加文本框

我正在动态创建一个文本框。 我的网格中有2列。 如果另一个文本框值=“茶”,我想在行中添加新文本框。 我想创建新的文本框到相应的行文本框值更改。 我无法使用Tag在此处获取所选行。 因为我已经出于某种目的使用了Tag。 我对Tag不太了解。 无论如何,如何将新文本框添加到column1到相应的行? 这是我的代码..

public int count = 1; public TextBox txt1; private void btn_addnew_Click(object sender, RoutedEventArgs e) { //Creating Rows.. RowDefinition row0 = new RowDefinition(); row0.Height = new GridLength(40); grid1.RowDefinitions.Add(row0); //Creating columns.. ColumnDefinition col0 = new ColumnDefinition(); ColumnDefinition col1 = new ColumnDefinition(); col0.Width = new GridLength(150); col1.Width = new GridLength(250); grid1.ColumnDefinitions.Add(col0); grid1.ColumnDefinitions.Add(col1); int i = count; //1st Column TextBox txt1 = new TextBox(); txt1.Margin = new Thickness(10, 10, 0, 0); Grid.SetRow(txt1, i); Grid.SetColumn(txt1, 0); txt1.Tag = txt1; txt1.MouseEnter+=txt1_MouseEnter; txt1.TextChanged += txt1_TextChanged; grid1.Children.Add(txt1); count++; } private void txt1_MouseEnter(object sender, MouseEventArgs e) { txt1 = ((TextBox)sender).Tag as TextBox; popup.IsOpen = true; } public TextBox txt2; private void txt1_TextChanged(object sender, TextChangedEventArgs e) { if (txt1.Text.ToString() == "Tea") { txt2 = new TextBox(); //How to set row here? Grid.SetRow(txt2, ??); Grid.SetColumn(txt2, 1); txt2.Margin = new Thickness(10, 10, 0, 0); grid1.Children.Add(txt2); } else { grid1.Children.Remove(txt2); } } 

如果你只想实现这一点,那么更优雅的方法是将用户控件添加到你的应用程序中,如下所示:

               

然后在你的btn_addnew_Click()方法中,你只需要将这个usercontrol添加到用户Grid并为其分配行和列。 显示/隐藏文本框将由用户控件本身处理。

  var userControl = new MyUserControl(); userControl .Margin = new Thickness(10, 10, 0, 0); Grid.SetRow(userControl , i); grid1.Children.Add(userControl ); 

或者如果你想为textbox1获得Grid.Row的值,你可以直接得到它:

  if (textbox1 != null) { int row = (int)textbox1.GetValue(Grid.RowProperty); Grid.SetRow(txt2, row); } 

附加属性可用于存储此类信息,因此在类中定义附加属性

  public static int GetGridRow(DependencyObject obj) { return (int)obj.GetValue(GridRowProperty); } public static void SetGridRow(DependencyObject obj, int value) { obj.SetValue(GridRowProperty, value); } // Using a DependencyProperty as the backing store for GridRow. This enables animation, styling, binding, etc... public static readonly DependencyProperty GridRowProperty = DependencyProperty.RegisterAttached("GridRow", typeof(int), typeof(ViewModel), new PropertyMetadata(0)); 

然后用它来存储行的值

 private void btn_addnew_Click(object sender, RoutedEventArgs e) { //1st Column TextBox txt1 = new TextBox(); Grid.SetRow(txt1, i); SetGridRow(text1, i); ... grid1.Children.Add(txt1); count++; } 

然后在需要时使用它

 //How to set row here? Grid.SetRow(txt2, GetGridRow(txt1)); Grid.SetColumn(txt2, 1);