我使用以下代码创建动态TextBox
和Button
动态:
Button btnClickMe = new Button(); btnClickMe.Content = "Click Me"; btnClickMe.Name = "btnClickMe"; btnClickMe.Click += new RoutedEventHandler(this.CallMeClick); someStackPanel.Childern.Add(btnClickMe); TextBox txtNumber = new TextBox(); txtNumber.Name = "txtNumber"; txtNumber.Text = "1776"; someStackPanel.Childern.Add(txtNumber);
我联系了Click Me
按钮的点击事件.单击我按钮甚至被正确触发.但是我找不到TextBox
我动态输入的内容.
这是我点击我的活动:
protected void ClickMeClick(object sender, RoutedEventArgs e) { // Find the phone number TextBox txtNumber = this.someStackPanel.FindName("txtNumber") as TextBox; if (txtNumber != null) { string message = string.Format("The number is {0}", txtNumber.Text); MessageBox.Show(message); } else { MessageBox.Show("Textbox is null"); } }
我该TextBox
txtNumber
怎么找到?
Josh G有修复此代码的线索:使用RegisterName().
这里有三个好处:
不使用成员变量来保存对动态创建的TextBox的引用.
编译.
完整的代码.
using System; using System.Windows; using System.Windows.Controls; namespace AddControlsDynamically { public partial class Window1 : Window { public void Window_Loaded(object sender, RoutedEventArgs e) { GenerateControls(); } public void GenerateControls() { Button btnClickMe = new Button(); btnClickMe.Content = "Click Me"; btnClickMe.Name = "btnClickMe"; btnClickMe.Click += new RoutedEventHandler(this.CallMeClick); someStackPanel.Children.Add(btnClickMe); TextBox txtNumber = new TextBox(); txtNumber.Name = "txtNumber"; txtNumber.Text = "1776"; someStackPanel.Children.Add(txtNumber); someStackPanel.RegisterName(txtNumber.Name, txtNumber); } protected void CallMeClick(object sender, RoutedEventArgs e) { TextBox txtNumber = (TextBox) this.someStackPanel.FindName("txtNumber"); string message = string.Format("The number is {0}", txtNumber.Text); MessageBox.Show(message); } } }
另一种方法是将关联设置TextBox
为Button Tag
实例化时.
btnClickMe.Tag = txtNumber;
这样您就可以在事件处理程序中将其检索回来.
protected void ClickMeClick(object sender, RoutedEventArgs e) { Button btnClickMe = sender as Button; if (btnClickMe != null) { TextBox txtNumber = btnClickMe.Tag as TextBox; // ... } }
您可以通过注册文本框的名称来使原始点击处理程序正常工作:
someStackPanel.RegisterName(txtNumber.Name, txtNumber);
然后,这将允许您在StackPanel上调用FindName并找到TextBox。