Search code examples
c#wpfimagecontentcontrol

Get ContentControl Children


How can I iterate over the Images in the ContentControls?

<Canvas x:Name="canvas" >

    <ContentControl Style="{StaticResource DesignerItemStyle}">
        <Image IsHitTestVisible="True" Source="Media/cross.png"   />
    </ContentControl>

    <ContentControl Style="{StaticResource DesignerItemStyle}">
        <Image IsHitTestVisible="True" Source="Media/cross.png"   />
    </ContentControl>

</Canvas>

My try does not work:

var ccs = canvas.Children;
foreach (ContentControl c in ccs)
{
   for (int i = 0; i < VisualTreeHelper.GetChildrenCount(c); i++)
   {
     var child = VisualTreeHelper.GetChild(c, i);
   }
}

Solution

  • Use LINQ:

    var images = canvas.Children
        .OfType<ContentControl>()
        .Select(cc => cc.Content as Image)
        .Where(img => img != null);
    

    As a note, setting IsHitTestVisible="True" is redundant. True is the default value.