How to get list of controls in a group box in WPF

In standard WinForms development, I would do the following:

foreach (Control in groupBox1.Controls)
{
     MessageBox.Show(c.Name);
}

      

How does a guy do it in WPF? I have a Grid inside a GroupBox and several controls in the grid (buttons, etc.), but cannot figure out how to get each control.

+2


source to share


3 answers


As MSDN advises, you will need to iterate over the controls as children GroupBox

. Also note that you usually need to add Grid

to yours GroupBox

to add new controls to this GroupBox

. Thus, you will need to get the children Grid

in this, GroupBox

and iterate through something like this:

//iterate through the child controls of "grid"
int count = VisualTreeHelper.GetChildrenCount(grid);
            for (int i = 0; i < count; i++)
            {
              Visual childVisual = (Visual)VisualTreeHelper.GetChild(grid, i);
                if (childVisual is TextBox)
                {
                    //write some logic code
                }
               else
               {

               }
            }

      



You may find this useful: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/93ebca8f-2977-4c36-b437-9c82a22266f6

+6


source


The simplified code would be something like



foreach (Control control in Grid.Children)
 {
  //Code here for what you want to do.
 }

      

+1


source


Instead, .Controls

you will be looking for a property .Children

.

Also, it will only result in first order children being returned. You will want to recursively find all children of all controls if you really want all descendants GroupBox

.

-2


source







All Articles