2

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
}
2
  • You do not have to create method for each of them. One method for all them is just enough in your case. Commented Feb 28, 2019 at 15:17
  • In WPF all components lives into others components commonly Panel (or derived components like a Grid, StackPanel, etc.) you have to get all childs of panel, and so can obtain all Checkbox into panle and validate if any is checked or not, a good solution is implement the answer of @Shawn Commented Feb 28, 2019 at 15:22

1 Answer 1

12

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.