#1,190 – VisualChildrenCount and GetVisualChild
October 29, 2014 1 Comment
A 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()); }
Pingback: Dew Drop – October 30, 2014 (#1888) | Morning Dew