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; } }
