无法使用C#和XAML在按钮上单击事件的单击事件,无法动态创建的TextBox.TEXT数据



我很难从C#/XAML中的文本框中获取文本。我正在运行2种方法 - 第一种方法可以创建一个stackpanel并在其中添加2个文本框,而第二个方法仅是从2个文本框中获取文本,然后将其分配给我在其他地方定义的类对象。但是 - 当我尝试获取TextBox.Text时,它说它不识别我用于文本框对象的变量名称。谁能提供有关我做错什么的线索?这是我的代码。

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;
    }

这里的问题是tb1.text和tb2.Text尚未识别。为什么?

声明

TextBox tb1;
TextBox tb2;

createstackpanel()级别的CC_1函数外部。

初始化

tb1 = new TextBox();
tb2 = new TextBox();

createstackpanel()函数内部。

tb1tb2createstackpanel方法中声明。他们无法在SendTextToClass_Click方法中访问。

P.S。我认为在这种情况下使用动态创建的文本框并不是DOOG的想法。您的代码的最终目标是什么?

文本框列表示例:

// 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

最新更新