hello there is a code. I want to go over the elements of the grid namely by Image

foreach ( var item in mainGrid.Children) { if (item.GetType() == Image) { } } 

I eat so but that does not go as right

 if (item.Equals(typeof(Image))) { } 

it seems so normal, but now how to remove the image from Image which is set as Source

that is, I think to remove the source so

 oneImage.Source = null; 

but how to organize it in a cycle

    1 answer 1

    You can use the VisualTreeHelper class to work with the visual tree.

    The GetChild method allows you to get the children of the specified element, but already there you are doing everything you want with the children.

    xaml:

     <Grid x:Name="grid1"> <Grid.RowDefinitions> <RowDefinition /> <RowDefinition /> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Image Grid.Row="0" Source="image/1.png"/> <Image Grid.Row="1" Source="image/2.png" /> <Button Grid.Row="3" Content="Clear Images" Click="Button_Click" /> </Grid> 

    code-behind:

     private void Button_Click(object sender, RoutedEventArgs e) { int childrenCount = VisualTreeHelper.GetChildrenCount(grid1); for (int i = 0; i < childrenCount; i++) { var current = VisualTreeHelper.GetChild(grid1, i); var image = current as Image; if (image != null) { image.Source = null; } } } 


    Well, or just:

     foreach (var gridChild in grid1.Children) { var image = gridChild as Image; if (image != null) { image.Source = null; } } 

    Update

    To get straight all-all Image that are in the grid, regardless of the level of nesting, you can use this method :

     public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject { if (depObj != null) { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++) { DependencyObject child = VisualTreeHelper.GetChild(depObj, i); if (child != null && child is T) { yield return (T)child; } foreach (T childOfChild in FindVisualChildren<T>(child)) { yield return childOfChild; } } } } 

    The code for pressing the button will look like this:

     private void Button_Click(object sender, RoutedEventArgs e) { foreach (Image image in FindVisualChildren<Image>(grid1)) { image.Source = null; } } 

    enter image description here

    • clear thanks fcwf - Sasuke
    • @ Sanitary Please! - trydex
    • listen and how to get the image in this same grid but attached to Label - Sasuke
    • @ Sanitary, supplemented the answer. - trydex
    • wow thank you very much - Sasuke