0

I'm trying to get the IsChecked value from all Checkboxes in a groupbox. I keep searching around and everyone seems to point to yourControl.Controls.OfType().... The problem is, I cannot get controls off of my groupbox. I get "GroupBox does not contain a definition for Controls" error whenever I try to code it.

I am very new to this, so sorry if this has been answered somewhere else that I've looked and it just wasn't clicking for me. I am creating a WPF C# app in Visual Studio 2017.

I have included part of my xaml

<GroupBox Name="Computers" Header="Computers" HorizontalAlignment="Left" 
Height="315" Margin="21,78,0,0" VerticalAlignment="Top" Width="216">
<CheckBox Name="Training01CB" Content="Training01" 
HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" 
Height="15" Width="78" IsChecked="False"/>
<CheckBox Name="Training02CB" Content="Training02" 
HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" 
Height="15" Width="78" IsChecked="False"/>
</GroupBox>

I'd like to do something like this: foreach(Computers.Controls.OfType().Checked) { run private code here }

Paul Toone
  • 123
  • 1
  • 3
  • 12

1 Answers1

2

The XAML you have posted is invalid and won't compile. You can only set the Content of the GroupBox to a single object.

However, if you set it to a Panel and add the CheckBox elements to this Panel, you could iterate through its Children property like this:

Panel panel = Computers.Content as Panel;
if (panel != null)
{
    foreach (CheckBox checkBox in panel.Children.OfType<CheckBox>())
    {
        //...
    }
}

XAML:

<GroupBox Name="Computers" Header="Computers">
    <StackPanel>
        <CheckBox Name="Training01CB" Content="Training01" IsChecked="False"/>
        <CheckBox Name="Training02CB" Content="Training02" IsChecked="False"/>
    </StackPanel>
</GroupBox>
mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thank you very much! I have been trying to read and figure things out on my own but I was banging my head against the wall. You saved me! Thank you so much! – Paul Toone Sep 20 '18 at 14:43