Douglas Anderson
Douglas Anderson

Reputation: 4690

How to get a list of controls in a groupbox 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 this in WPF? I have a Grid inside the GroupBox and a number of controls in the grid (buttons etc.) but can't seem to figure out how to get each control.

Upvotes: 2

Views: 16719

Answers (4)

I know this is an old thread and that the answer marked as accepted works, but it could be simpler (and simple is better). Anthony got the idea but failed to mention that one needs to iterate on the grid inside the GroupBox and failed to explain how to get there.

In XAML give a name to the main grid inside the GroupBox control (here assuming you named it "GroupBoxGridName"). This will allow you to search for controls inside this Grid including the controls inside any grid in the main group box grid (recursive).

Then do this in the C# code:

foreach (ControlType myControl in GroupBoxGridName.ChildrenOfType<ControlType>)
{
        MessageBox.Show(MyControl.Name);
}

Where ControlType can be general as Control or a defined type like TextBox or ComboBox or whatever.

Upvotes: 0

Anthony
Anthony

Reputation: 97

Simpler code would be something like

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

Upvotes: 1

Derar
Derar

Reputation: 470

As MSDN advises, you will need to iterate the controls as children of the GroupBox. Also, note that you usually need to add a Grid into your GroupBox to be able to add new controls into that GroupBox. So you will need to get the children of the Grid in that GroupBox and iterate through them, 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 might find this useful: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/93ebca8f-2977-4c36-b437-9c82a22266f6

Upvotes: 6

JustLoren
JustLoren

Reputation: 3234

Instead of .Controls, you'll be looking for the .Children property.

Additionally, that will only return first order children. You'll want to recursively find all children of all controls if you truly want all descendants of the GroupBox.

Upvotes: -3

Related Questions