#1,190 – VisualChildrenCount and GetVisualChild

FrameworkElement provides the VisualChildrenCount property and the GetVisualChild method, typically used during layout to walk through the child elements of the element participating in layout.  When you create a custom control that derives from FrameworkElement, you typically override both members, providing values that make sense for your control.

Below, we use these members to get a report of the visual children of a custom StackPanel.  (Because neither member is public, we override StackPanel to allow access).

XAML is:

        <loc:MyStackPanel x:Name="aStackPanel">
            <Label Content="Hi there"/>
            <Button Content="Click me"/>

        <Button Content="Visual Children" Click="Button_Click"/>

Code-behind is:

        private void Button_Click(object sender, RoutedEventArgs e)
            StringBuilder sbMsg = new StringBuilder();

            sbMsg.Append("Children of MyStackPanel:\n");
            int childCount = aStackPanel.MyVisualChildrenCount;
            for (int i = 0; i < childCount; i++)
                Visual child = aStackPanel.MyGetVisualChild(i);
                sbMsg.AppendFormat(" - {0}\n", child.GetType().ToString());


Results at run-time: