尝试如下,
CustomControl:
<UserControl x:Class='SilverlightApplication3.MainPage'
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
d:DesignWidth='640'
d:DesignHeight='480'>
<StackPanel x:Name="LayoutRoot" Background="White">
<Button x:Name="btnWalkTree"
Content="Walk Tree"
Click="btnWalkTree_Click"/>
<Border CornerRadius="10" Background="Yellow">
<TextBlock x:Name="tbName1"
Text="Santa Clause"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="3" />
</Border>
<Border CornerRadius="10" Background="AliceBlue">
<TextBlock x:Name="tbName2"
Text="Mickey Mouse"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="3" />
</Border>
<Border CornerRadius="10" Background="Green">
<TextBlock x:Name="tbName3"
Text="The Tooth Fairy"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Margin="3" />
</Border>
</StackPanel>
</UserControl>
从自定义控件获取孩子的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void btnWalkTree_Click(object sender, RoutedEventArgs e)
{
this.WalkChildren(this);
}
private void WalkChildren(DependencyObject depObject)
{
string name = String.Empty;
FrameworkElement element = depObject as FrameworkElement;
if (element != null)
{
name = element.Name;
}
int childCount = VisualTreeHelper.GetChildrenCount(element);
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
this.WalkChildren(VisualTreeHelper.GetChild(element, i));
}
}
}
}
}
引用自VisualTreeHelper