#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:

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

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

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());
            }

            MessageBox.Show(sbMsg.ToString());
        }

Results at run-time:
1190-001

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,190 – VisualChildrenCount and GetVisualChild

  1. Pingback: Dew Drop – October 30, 2014 (#1888) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: