在我的应用程序中,我在运行时创建了一个文本框,这里是代码
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.
答案 0 :(得分:2)
我为你写了一个简单的例子:
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);
}
}
}
答案 1 :(得分:1)
使用以下代码:
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);
[没有把它带到tb var]。
这用于从文本框中获取其值已分配给运行时的文本。
答案 2 :(得分:1)
你应该声明你的控件,然后调用使控件可访问的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);