I have multiple images that I want to loop over and set properties of.
Snippet from the xaml, as you can see their names follow up: Life1, Life2, ...
<StackPanel Orientation="Horizontal">
<Image x:Name="Life1"></Image>
<Image x:Name="Life2"></Image>
<Image x:Name="Life3"></Image>
</StackPanel>
What I want is a way to loop over them and set properties.
for (int i = 1; i <= 3; i++) {
Life1.Source = ...
}
How can I add the value of int i to the base name of "Life" and have it interpreted as one of the images?
Thanks in advance!
If I understand you correctly, you have a series of named images in your page and you wish to set the properties for each.
Assuming you have various images in your project stored as Life1, Life2, Life3, etc, then you're really just constructing the name for them based on the prefix ("Life") and an index (I).
Try this:
for (int i=1; i<limit; i++)
{
string name = "Life" + i.ToString();
Image img = (Image)this.FindName(name);
// set properties of img here
}
Assuming that this
refers to a current page in your app, this will search the child elements for one with the specified name.
An alternative is simply to iterate over every image in the stackpanel.
If you name the panel, say, "ImageList", then your code can look like this:
foreach (Image item in ImageList.Children)
{
// do stuff to item here
}
If necessary you may query item
for its name, and set the properties accordingly.