简体   繁体   中英

How can I remove Child UIElement from a Grid by lambda?

Here is the XAML:

<Grid x:Name="G">
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <CheckBox Grid.Column="0"></CheckBox>
        <CheckBox Grid.Column="1" IsChecked="True"></CheckBox>
        <CheckBox Grid.Column="2" IsChecked="True"></CheckBox>
        <CheckBox Grid.Column="3"></CheckBox>
    </Grid>

I wanna remove all the CheckBox in the Grid which IsChecked is true.

So I wrote the code like this:

var RemoveList=G.Children.OfType<CheckBox>().Where(Child => Child.IsChecked == true);
foreach (CheckBox CB in RemoveList.ToList())
      {
      G.Children.Remove(CB);
      }

I think my code is redundant with a var RemoveList and has to change it to the List.

I want to find a way just remove the UIElement only by one line code and makes me learns more about the Lambda.

Is there any way to do this? Thank you.

G.Children
    .OfType<CheckBox>()
    .Where(child => child.IsChecked == true)
    .ToList()
    .ForEach(child => G.Children.Remove(child));

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