Sofia Bo
Sofia Bo

Reputation: 779

How to get all checked checkboxes in WPF?

I tried to find any solutions for this problem but I did not succeed. I only found solutions for WinForms which do not work for WPF.

I have a simple form that has some checkboxes on it. I want to know what checkboxes are checked. The only way I know to do it is to create a method for each checkbox like

"Checkbox1_Checked(object sender, RoutedEventArgs e)" 

and add the name of a checkbox in a List (and remove it from list if the box is unchecked).

Is there any other way I can get all the checked checkboxes? Something like

foreach (var cb in this.Controls)
{
    if (cb is Checkbox && cb.IsCheked()) // blablabla
}

Upvotes: 2

Views: 4162

Answers (1)

devsmn
devsmn

Reputation: 1040

You could use LINQ for this. Assuming that you named the parent control grid, for example.

var list = this.grid.Children.OfType<CheckBox>().Where(x => x.IsChecked == true);

Or, if you don't want to name it - assuming that your container derives from Panel (e.g Grid, StackPanel...) - simply cast it like this

var list = (this.Content as Panel).Children.OfType<CheckBox>().Where(x => x.IsChecked == true);

Upvotes: 12

Related Questions