Reputation: 1543
So i have this block of code and i have a button called AddNewButton which adds a StackPanel into a already created StackPanel called MainStackPanel which is irrelevant but the "GroupPanel" has child controls such as "GroupName", "GroupTextBox" and "GroupEdit".
Now the "GroupEdit" button has a click event that runs the void named "GroupEdit_Click" and in that void i use Button GroupEdit1 = sender as Button;
Now this works and makes me able to access the buttons properties and change content but my problem is: How do i access the other controls such as "GroupPanel", "GroupName" and "GroupTextBox". I will use the AddNewButton a few times so when i access the separate controls they need to be accessed seperately
I tried to get rid of as much unnecessary code.
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;
}
}
Upvotes: 0
Views: 71
Reputation: 369
You could maintain a private List of your dynamically added GroupEdit controls and assign them numbered tags.
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;
}
}
Upvotes: 1