简体   繁体   中英

Find control property by name

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? Eg if I have a predefined list of checkboxes' names.

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.

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