1

I have a StackPanel with some WrapPanel . inside each WrapPanel located two element:

<StackPanel FlowDirection="RightToLeft" Grid.Column="2" Grid.Row="1" Name="check_boxes_layout">
    <WrapPanel>
        <CheckBox Name="chk1" Checked="Checked_Changed" Unchecked="Unchecked"></CheckBox>
        <Rectangle Width="50" Fill="Red" Name="rec1" Margin="10 2 2 2"/>
    </WrapPanel>
    <WrapPanel>
        <CheckBox Name="chk12" Checked="Checked_Changed" Unchecked="Unchecked"></CheckBox>
        <Rectangle Width="50" Fill="Blue" Name="rec2" Margin="10 2 2 2"/>
    </WrapPanel>
<StackPanel/>

I want to get all children of type check box .how can i do this?

foreach (var item in check_boxes_layout.Children.OfType<CheckBox>())
{
    //this code just return Wrap Panel
}

Thank You in Advance.

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
KF2
  • 9,887
  • 8
  • 44
  • 77

2 Answers2

2

Use this recursive function:

List<UIElement> GetAllChildren(Panel c)
{
    List<UIElement> list = c.Children.Cast<UIElement>().ToList();
    foreach( var elem in list.OfType<Panel>())
        list.AddRange(GetChildren(elem));
    return list;
}

No you can say:

foreach (var item in GetAllChildren(check_boxes_layout).OfType<CheckBox>())
{
    //...
}
Mohammad Dehghan
  • 17,853
  • 3
  • 55
  • 72
0

I got it first loop through warp panels and get its child

 foreach (WrapPanel warppanel in check_boxes_layout.Children)
 {
     foreach (var item in warppanel.Children.OfType<CheckBox>)
     {
          .
          .
          .
     }
 }
Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
KF2
  • 9,887
  • 8
  • 44
  • 77
  • What if you have another `Panel` or `Grid` inside the `WrapPanel`? My answer handles any level of nesting. – Mohammad Dehghan Mar 03 '13 at 09:46
  • @MD.Unicorn, this (OP's) answer does answer OP's *current* question. None the less it's not a very good solution because it depends on the current layout: it will fail if new panels are introduced. That is, it's not future-proof. – Cosmin Prund Mar 03 '13 at 09:50