所以我有這塊代碼,我有一個名爲AddNewButton的按鈕,它將一個StackPanel添加到一個名爲MainStackPanel的已創建的StackPanel中,這是無關緊要的,但「GroupPanel」具有諸如「GroupName」,「GroupTextBox」和「GroupEdit 」。如何編輯在運行時在C#中創建的控件?
現在「GroupEdit」按鈕有一個點擊事件,運行名爲「GroupEdit_Click」的void,並且在那個void我使用Button GroupEdit1 = sender as Button;
現在這個工作,並且使我能夠訪問按鈕屬性和更改內容,但我的問題是:我是否可以訪問其他控件,如「GroupPanel」,「GroupName」和「GroupTextBox」。我將使用AddNewButton幾次,因此當我訪問單獨的控件時,需要單獨訪問它們。
我試圖擺脫儘可能多的不必要的代碼。
private void AddNewButton_Click(object sender, RoutedEventArgs e)
{
StackPanel GroupPanel = new StackPanel();
TextBlock GroupName = new TextBlock();
GroupName.Text = "Group ";
TextBox GroupTextBox = new TextBox();
GroupTextBox.Visibility = Visibility.Collapsed;
Button GroupEdit = new Button();
GroupEdit.Content = "Edit Group";
GroupEdit.Click += new RoutedEventHandler(GroupEdit_Click);
GroupPanel.Children.Add(GroupName);
GroupPanel.Children.Add(GroupTextBox);
GroupPanel.Children.Add(GroupEdit);
}
private void GroupEdit_Click(object sender,RoutedEventArgs e)
{
Button GroupEdit1 = sender as Button;
GroupEdit1.Content = "Done";
//Now how do i access these controls?
GroupName.Visibility = Visibility.Collapsed;
GroupTextBox.Visibility = Visibility.Visible;
}
}
新控件的範圍侷限於按鈕點擊,因此您必須使用GroupEdit_Click事件處理函數遍歷表單的控件。各種各樣的發現過程。 – JamieMeyer
刪除所有這些,並使用正確的XAML和數據綁定,無論您嘗試做什麼。 –