-5

I have some images on a window, how can I loop around them all to set the image to cover.jpg?

public partial class MainWindow : Window
{
    int score;
    List<int> lst = new List<int>();

    public MainWindow()
    {
        InitializeComponent();
        foreach(Image img in Grid.)
    }        
}
TheLethalCoder
  • 6,668
  • 6
  • 34
  • 69
Muhammad Jazab
  • 24
  • 2
  • 11

3 Answers3

0

Check the following question.

WPF: How do I loop through the all controls in a window?

You should be able to do it like this:

public MainWindow()
{
 InitializeComponent();

 IEnumerable<Image> images = GetChildren(Grid).OfType<Image>();
 if (images != null)
 {
    BitmapImage bi = new BitmapImage(new Uri("pic.png", UriKind.Relative));
    foreach (Image image in images)
    {
        image.Source = bi;
    }
  }
}

public static IEnumerable<Visual> GetChildren(Visual parent, bool recurse = true)
{
  if (parent != null)
  {
      int count = VisualTreeHelper.GetChildrenCount(parent);
      for (int i = 0; i < count; i++)
      {
         // Retrieve child visual at specified index value.
        var child = VisualTreeHelper.GetChild(parent, i) as Visual;

        if (child != null)
        {
            yield return child;

            if (recurse)
            {
                foreach (var grandChild in GetChildren(child, true))
                {
                    yield return grandChild;
                }
            }
          }
       }
    }
  }

  <Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="300" Width="300">
<Grid x:Name="Grid">
 <Image ... />
....
Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
0

Code Behind code behind Desginer designer as far sa i understood, this is what you need, just change the hardcoded location to your cover.jpg.

ShadyOverflow
  • 85
  • 3
  • 11
0

I'd advise not doing that in the code behind but instead to use MVVM principles and use a GridView/ ListView with an ItemSource bound to the ImagesList (you'd have to make it an ObservableCollection instead of a list). If you need more data, encapsulate the image in a class that holds the required additional data. This way you don't need to loop, and everything happens "on it's own"

Oyiwai
  • 449
  • 1
  • 3
  • 20