0

I have declared checkboxes in a grid layout in XAML on a UserControl.

<CheckBox Content="Boo" Grid.Column="0" Grid.Row="0"/>
<CheckBox Content="Hoo" Grid.Column="0" Grid.Row="1"/>

I want to somehow iterate over all these checkboxes in C#. How would I do this?

Thanks,

AlphaWolf
  • 183
  • 4
  • 16
  • The answer to [this question](http://stackoverflow.com/questions/10279092/how-to-get-children-of-a-wpf-container-by-type) might be helpful – allonym Oct 04 '14 at 00:29

1 Answers1

2

There souldn't be the need to access them programatically. You should use a ViewModel and bind properties to the checkboxes.

public class SomeViewModel : INotifyPropertyChanged
{
    private bool isCheckBoxOneChecked;

    public bool IsCheckBoxOneChecked
    {
        get { return isCheckBoxOneChecked; }
        set
        {
            if (value.Equals(isCheckBoxOneChecked))
            {
                return;
            }

            isCheckBoxOneChecked = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

<CheckBox IsChecked="{Binding IsCheckBoxOneChecked}" Content="Boo" Grid.Column="0" Grid.Row="0"/>
<CheckBox Content="Hoo" Grid.Column="0" Grid.Row="1"/>

You also have to set the DataContext like this:

this.DataContext = new SomeViewModel();

That's also possible via xaml.

Then you simply set the IsCheckBoxOneChecked property to true and the checkbox gets checked automatically. If the user unchecks the checkbox the property also gets set to false and vice versa.


Take a look over here: Model-View-ViewModel (MVVM) Explained


Nevertheless, if you set the Name property of your Grid you can iterate over all children:

// Grid is named 'MyGrid'
foreach (var child in this.MyGrid.Children)
{
    if (child is CheckBox)
    {
        var checkBox = child as CheckBox;

        // Do awesome stuff with the checkbox
    }
}
The-First-Tiger
  • 1,574
  • 11
  • 18