bd1与cp1为控件模板中的元素,bd1与cp1不存在父级parent元素。但是templatedParent将他们与
contentControl进行了关联,拥有共同的模板父级元素
<ContentControl Name="contentControl">
<!-- 控件模板 -->
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<Border Name="bd1">
<ContentPresenter Name="cp1" ContentSource="Content"/>
</Border>
</ControlTemplate>
</ContentControl.Template>
<!-- 数据模板 -->
<ContentControl.ContentTemplate>
<DataTemplate>
<Border Name="bd2">
<ContentPresenter Name="cp2" Content="{Binding}" />
</Border>
</DataTemplate>
</ContentControl.ContentTemplate>
<!-- 逻辑孩子 -->
<Button Name="btn">按钮</Button>
</ContentControl>
privatevoid Button_Click(object sender, RoutedEventArgs e)
{
var bd1 = (Border)contentControl.Template.FindName("bd1", contentControl);
var cp1 = (ContentPresenter)contentControl.Template.FindName("cp1", contentControl);
var bd2 = (Border)contentControl.ContentTemplate.FindName("bd2", cp1);
var cp2 = (ContentPresenter)contentControl.ContentTemplate.FindName("cp2", cp1);
PrintInfo(bd1, cp1, bd2, cp2, btn);
}
void PrintInfo(paramsFrameworkElement[] eles)
{
string s ="";
foreach (var ele in eles)
s +=String.Format("{2}\r\nParent: {0}\r\nTemplatedParent: {1}\r\n\r\n", ele.Parent, ele.TemplatedParent, ele.Name);
MessageBox.Show(s);
}
bd1
Parent: //border属于模板中的元素,没有父级元素
TemplatedParent: System.Windows.Controls.ContentControl: 按钮
cp1
Parent: System.Windows.Controls.Border
TemplatedParent: System.Windows.Controls.ContentControl: 按钮
bd2
Parent:
TemplatedParent: System.Windows.Controls.ContentPresenter
数据模板拥有共同的父级模板元素,内容呈现元素
cp2
Parent: System.Windows.Controls.Border
TemplatedParent: System.Windows.Controls.ContentPresenter
btn
Parent: System.Windows.Controls.ContentControl: 按钮
TemplatedParent: