简体   繁体   中英

Cannot get Controls from GroupBox

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 }

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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