获取在运行时创建的文本框的文本
本文关键字:文本 创建 运行时 获取 | 更新日期: 2023-09-27 18:08:05
在我的应用程序中,我在运行时创建了一个文本框,下面是代码
TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Height = 20;
bt.SetValue(Grid.ColumnProperty, 1);
bt.SetValue(Grid.RowProperty, 0);
temp_grid.Children.Add(bt);
那么,如何在用户键入内容并输入后获取该文本框的文本呢?我不知道怎么做,我试了试
var tb = (FrameworkElement)this.FindName("population_textbox") as TextBox;
Console.Write(tb.Text);
错误提示:
Exception has been thrown by the target of an invocation.
我给你写一个简单的例子:
TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Text = "some";
bt.Height = 20;
main_Grid.Children.Add(bt);
foreach (TextBox txt in main_Grid.Children)
{
if (txt is TextBox)
{
if ((txt as TextBox).Name == "population_textbox")
{
MessageBox.Show((txt as TextBox).Text);
}
}
}
您应该声明您的控件,然后调用RegisterName方法,使控件可访问,然后您可以从窗口作用域的任何地方引用控件名称:
TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Height = 20;
bt.SetValue(Grid.ColumnProperty, 1);
bt.SetValue(Grid.RowProperty, 0);
temp_grid.Children.Add(bt);
this.RegisterName(bt.Name, bt);
var tb = this.FindName("population_textbox") as TextBox;
Console.Write(tb.Text);
使用以下代码:
this.RegisterName("bt", textBox);
也试一试:
var tb = (FrameworkElement)this.FindName("population_textbox");
或直接写入:
TextBox bt = new TextBox();
bt.Name = "population_textbox";
bt.Height = 20;
bt.SetValue(Grid.ColumnProperty, 1);
bt.SetValue(Grid.RowProperty, 0);
temp_grid.Children.Add(bt);
Console.Write(bt.Text);
[不服用].
用于从文本框中获取文本,该文本框的值是在运行时指定的。