Get all Image Elements within a Grid->Canvas using LINQ?
i'm using a Grid within my Application which Contain some Canvas Elements which Contain some Images or Textblocks.
e.g.:
<Grid>
&开发者_如何学编程lt;Canvas>
<Image />
<Image />
</Canvas>
<Canvas>
<Textblock />
<Textblock />
</Canvas>
</Grid>
Now i need to get all Image Elements within the Grid. Currently i'm using several foreach loops and if-statements to achive this. But i was asking myself if there isn't a more elegant way using LINQ so fetch all Image Elements from the Grid. But unfortunely my LINQ Knowledges aren't that well so i didn't found a way to get the to the Children of the Canvas Element.
Maybe someone has a good Solution to this.
Thanks in advance and kind regards
Kornelis
I added a Name to the Grid to reference in the link
<Grid Name="MyGrid">
Then this linq returns Images inside of canvases that are children of the Grid. I cast it as an object so that it could query every control that was in the Children collection.
IEnumerable<Image> results = (from c in MyGrid.Children.Cast<Object>()
where c.GetType() == typeof(Canvas)
select c).Cast<Canvas>()
.SelectMany(r => r.Children.Cast<object>()
.Where(c => c.GetType() == typeof(Image))).Cast<Image>();
精彩评论