[英]Unable to get dynamically created textbox.text data on button click event using c# and XAML
I'm having trouble getting text from a textbox in c#/xaml. 我在从c#/ xaml的文本框中获取文本时遇到麻烦。 I am running 2 methods - the first which creates a stackpanel and adds 2 textboxes to it and the second is intended to just take the text from the 2 textboxes and assign it to a class object I have defined elsewhere. 我正在运行2个方法-第一个方法创建一个堆栈面板并向其中添加2个文本框,第二个方法只是从2个文本框中获取文本并将其分配给我在其他地方定义的类对象。 However - when I try to get the textbox.text, it says it doesn't recognise the variable name I have used for the textbox object. 但是-当我尝试获取textbox.text时,它说它无法识别我用于textbox对象的变量名。 Can anyone offer any clue as to what I'm doing wrong? 谁能提供我做错事情的任何线索? Here's my code. 这是我的代码。
public void createstackpanel()
{
StackPanel myStackPanel = new StackPanel();
myStackPanel.Orientation = Windows.UI.Xaml.Controls.Orientation.Vertical;
MyTextBoxTextClass Text1 = new MyTextBoxTextClass ();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
tb1.Text = "My TextBox 1 Text";
tb2.Text = "My TextBox 2 Text";
myStackPanel.Children.Add(tb1);
myStackPanel.Children.Add(tb2);
}
private void CreateStackPanelButton_Click(object sender, RoutedEventArgs e)
{
//This gets pressed first
createstackpanel();
}
private void SendTextToClass_Click(object sender, RoutedEventArgs e)
{
//This gets pressed second. I have created the StoreMyText class elsewhere and it simply contains 2 properties - textbox1 and textbox2 (both strings)
StoreMyText mytext = new StoreMyText();
mytext.textbox1 = tb1.Text;
mytext.textbox2 = tb2.Text;
}
The issue here is that tb1.Text and tb2.Text aren't being recognised. 这里的问题是tb1.Text和tb2.Text无法识别。 Why? 为什么?
tb1
and tb2
declared in createstackpanel
method. tb1
和tb2
中声明createstackpanel
方法。 They can't accessed in SendTextToClass_Click
method. 它们无法使用SendTextToClass_Click
方法访问。
PS I think it's not doog idea to use dynamically created textboxes in this situation. PS:我认为在这种情况下使用动态创建的文本框并不是一个主意。 What is a final goal of your code? 您的代码的最终目标是什么?
List of textboxes sample: 文本框列表示例:
// class level declaration:
List<TextBox> textboxes = new List<TextBox>();
// createstackpanel method:
textboxes.Add(new TextBox() { Text = "textbox #1" });
textboxes.Add(new TextBox() { Text = "textbox #2" });
// SendTextToClass_Click method:
// some operation with textboxes list
Declare 宣布
TextBox tb1;
TextBox tb2;
outside the createstackpanel()
function in the Class
level. Class
级别的createstackpanel()
函数之外。
and initialize 并初始化
tb1 = new TextBox();
tb2 = new TextBox();
inside the createstackpanel()
function. 在createstackpanel()
函数中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.