2015-05-07 36 views
1

我無法從c#/ xaml中的文本框中獲取文本。我正在運行2個方法 - 第一個創建一個堆棧面板並向其中添加2個文本框,第二個方法旨在從2個文本框中獲取文本,並將其分配給我在別處定義的類對象。但是 - 當我嘗試獲取textbox.text時,它說它不能識別我用於文本框對象的變量名稱。任何人都可以提供任何線索,我做錯了什麼?這是我的代碼。無法動態創建textbox.text數據使用c#和XAML按鈕單擊事件

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沒有被識別。爲什麼?

回答

1

聲明

TextBox tb1; 
TextBox tb2; 

createstackpanel()功能之外的Class水平。

初始化

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

createstackpanel()函數內。

+0

根據下面的評論 - 該按鈕的想法是,用戶能夠繼續創建新的文本框(不會有默認文本,但他們自己輸入的文本)。因此,我希望用戶能夠控制多少個文本框由多少次點擊該按鈕所控制 – Ricardinho

+1

已更新我的答案。請指出這一點。 –

+0

完美 - 謝謝約翰 - 固定它:) – Ricardinho

1

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 
+1

那麼我如何獲得他們的信息,例如按鈕點擊?他們有什麼方法可以公開這些數據嗎? (我認爲創建方法作爲pubilc方法可能會這樣做...我錯了:)/:() – Ricardinho

+1

例如,您可以在類級別聲明這些文本框。 –

+1

問題是,我想繼續動態創建它們。該按鈕的想法是,用戶能夠繼續創建新的文本框(不會有默認文本,但它們自己輸入的文本)。因此,我希望用戶能夠控制多少文本框由多少次點擊該按鈕 – Ricardinho

相關問題