繁体   English   中英

在运行时如何编辑在C#中创建的控件?

[英]How do edit controls that were created in C# during runtime?

因此,我有这段代码,还有一个名为AddNewButton的按钮,该按钮将StackPanel添加到已创建的称为MainStackPanel的StackPanel中,这是不相关的,但“ GroupPanel”具有子控件,例如“ GroupName”,“ GroupTextBox”和“ GroupEdit”。

现在,“ GroupEdit”按钮具有一个单击事件,该事件运行名为“ GroupEdit_Click”的空白,在该空白中,我使用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控件的私有列表,并为其分配编号的标签。

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;
     }
}

暂无
暂无

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

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