繁体   English   中英

使用C#和XAML无法在按钮单击事件上获得动态创建的textbox.text数据

[英]Unable to get dynamically created textbox.text data on button click event using c# and XAML

我在从c#/ xaml的文本框中获取文本时遇到麻烦。 我正在运行2个方法-第一个方法创建一个堆栈面板并向其中添加2个文本框,第二个方法只是从2个文本框中获取文本并将其分配给我在其他地方定义的类对象。 但是-当我尝试获取textbox.text时,它说它无法识别我用于textbox对象的变量名。 谁能提供我做错事情的任何线索? 这是我的代码。

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无法识别。 为什么?

tb1tb2中声明createstackpanel方法。 它们无法使用SendTextToClass_Click方法访问。

PS:我认为在这种情况下使用动态创建的文本框并不是一个主意。 您的代码的最终目标是什么?

文本框列表示例:

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

宣布

TextBox tb1;
TextBox tb2;

Class级别的createstackpanel()函数之外。

初始化

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

createstackpanel()函数中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM