所以我有这个代码块,我有一个名为AddNewButton的按钮,它将一个StackPanel添加到一个名为MainStackPanel的已创建的StackPanel中,这个不相关但是" GroupPanel"具有子控件,例如" GroupName"," GroupTextBox"和" GroupEdit"。
现在" GroupEdit"按钮有一个click事件,它运行名为" GroupEdit_Click"的void。在那个虚空中,我使用Button GroupEdit1 = sender as Button;
现在这可以使我能够访问按钮属性并更改内容但我的问题是:如何访问其他控件,例如" GroupPanel",& #34;组名"和" 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;
}
}
答案 0 :(得分:1)
您可以维护动态添加的GroupEdit控件的私有List,并为它们分配编号标记。
private List<TextBox> dynamicGroupEdits = new List<TextBox>();
private void AddNewButton_Click(object sender, RoutedEventArgs e)
{
...
dynamicGroupEdits.Add(GroupEdit);
GroupEdit.Tag = dynamicGroupEdits.Count;
GroupPanel.Tag = GroupEdit.Tag;
GroupTextBox.Tag = GroupEdit.Tag;
...
}
private void GroupEdit_Click(object sender,RoutedEventArgs e)
{
...
tag = GroupEdit1.Tag;
// Loop through all child controls and set visibility according to tag
for each (var c in LogicalTreeHelper.GetChildren(GroupEdit1.Parent)
{
if(c is TextBox && c.Tag == tag)
c.Visible =Visibility.Visible;
else if(c is TextBlock && c.Tag == tag)
c.Visibility = Visibility.Collapsed;
}
}