问题
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.
回答1:
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>())
{
//...
}
回答2:
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>)
{
.
.
.
}
}
来源:https://stackoverflow.com/questions/15184276/get-uielement-children-from-multiple-parent