2011-09-14 55 views
-2

我對此很新,至今我還沒有找到任何解決方案在線解決我的問題。以編程方式添加文本框和按鈕 - >按鈕單擊無文本框內容的事件

我想使用控件通過編程添加它們,它的工作原理和內容顯示在窗口中,但只要我想通過按鈕保存內容,事件處理程序不會獲取傳遞給它的變量。

我有以下情況,我不知道我想念什麼。 (WPF4,EF,VS2010)

在XAML中我有一個網格,我想添加例如。一個文本框,並從後面的代碼按鈕像

<Grid Name="Grid1"> 
    <Grid.RowDefinitions> 
     <RowDefinition Height="100"></RowDefinition> 
     <RowDefinition Height="50"></RowDefinition> 
    </Grid.RowDefinitions> 

    <Grid.ColumnDefinitions> 
     <ColumnDefinition Width="75*"></ColumnDefinition> 
     <ColumnDefinition Width="25*"></ColumnDefinition> 
    </Grid.ColumnDefinitions> 

    <TextBox Grid.Row="2" Name="textBox1" /> 
</Grid > 

在後臺代碼:

private void CheckMatching() 
{ 
    TextBox textBox2 = new TextBox(); 
    textBox2.Text = "textbox to fill"; 
    textBox2.Name = "textBox2"; 

    Grid1.Children.Add(textBox2); 

    Button SaveButton = new Button(); 
    SaveButton.Name = "Save"; 
    SaveButton.Content = "Save"; 

    SaveButton.Click += new RoutedEventHandler(SaveButton_Click); 
    Grid1.Children.Add(SaveButton); 
} 

private void SaveButton_Click (object sender, RoutedEventArgs e) 
{ 
    // works fine 
    string ShowContent1 = textBox1.Text; 

    // It doesn't show up in intellisense, so I cant use it yet 
    string ShowContent2 = textBox2.Text; 
} 

我可以訪問XAML文本框或其他一切的XAML設定的內容,但我不獲取我在代碼隱藏中設置的其他內容。內容本身顯示在窗口中。

我已經嘗試了不同的方法。目前爲止沒有任何工作

回答

0

這個問題不是WPF問題,而是面向對象計算機編程非常基礎。

你怎麼能指望這是delcared和CheckMatching方法本地創建一個對象(textBox2)像SaveButton_Click另一種方法是可用?

爲此,您可以對其進行分類。

private TextBox textBox2; 

private void CheckMatching() 
{ 
    this.textBox2 = new TextBox(); 
    this.textBox2.Text = "textbox to fill"; 
    this.textBox2.Name = "textBox2"; 

    Grid1.Children.Add(this.textBox2); 
    ..... 
} 

private void SaveButton_Click (object sender, RoutedEventArgs e) 
{ 
     string ShowContent1 = textBox1.Text; // works fine 
     string ShowContent2 = this.textBox2.Text; // should work too 
} 

然後你也可以做到這一點WPF方式....

private void SaveButton_Click (object sender, RoutedEventArgs e) 
{ 
     string ShowContent1 = textBox1.Text; // works fine 
     string ShowContent2 = ((TextBox)Grid1.Children[1]).Text; // should work too 
} 
相關問題