1

I'm building C# WPF application with many CheckBoxes in it contained in different Grids. Here's an sample of the XAML code:

<Grid x:Name="grid1">
  <CheckBox x:Name="box1" Content="Box 1"/>
</Grid>
<Grid>
  <Grid x:Name="grid4">
    <CheckBox x:Name="box12" Content="Box 12"/>
  </Grid>
</Grid>

and so on.

In the code-behind I need to get a list of the boxes with property IsChecked="True" by count_btn_Click()

I've tried everything I could and found nothing. (Please remember I'm just an amateur so put more description if possible).

UPD1 (to the Charles Mager's comment): Is there a more simple way? E.g. if I have a predefined list of checkboxes' names.

GeeMitchey
  • 134
  • 1
  • 3
  • 13
  • use the *Controls* collection, and first test that each control is a Checkbox. – Pieter Geerkens May 24 '15 at 17:33
  • @PieterGeerkens there is no `Controls` collection in WPF. You need something like [this](http://stackoverflow.com/questions/974598/find-all-controls-in-wpf-window-by-type) – Charles Mager May 24 '15 at 17:35

1 Answers1

0

if I have a predefined list of checkboxes' names

How would you obtain that predefined list?

One example might look like this:

class MainWindow : Window
{
    private CheckBox[] _checkBoxes;

    public MainWindow()
    {
        InitializeComponent();

        _checkBoxes = 
        {
            box1,
            box12,
            // etc.
        };
    }
}

Then you should be able to obtain an enumeration of the objects through a simple LINQ filter:

_checkBoxes.Where(x => x.IsChecked);

For example:

foreach (CheckBox checkBox in _checkBoxes.Where(x => x.IsChecked))
{
    // do something with each checkBox value
}

I hope the above gets you pointed in the right direction. It's impossible to provide specific advice without a good, minimal, complete code example that clearly shows what you're trying to accomplish; if the above doesn't seem helpful enough, please edit your question so that it includes enough detail to understand what you really need help with.

Community
  • 1
  • 1
Peter Duniho
  • 68,759
  • 7
  • 102
  • 136