FrameworkElement.TemplatedParent 属性


获取对此元素的模板父级的引用。Gets a reference to the template parent of this element. 如果该元素不是通过模板创建的,则此属性无关。This property is not relevant if the element was not created through a template.

 property System::Windows::DependencyObject ^ TemplatedParent { System::Windows::DependencyObject ^ get(); };
public System.Windows.DependencyObject TemplatedParent { get; }
member this.TemplatedParent : System.Windows.DependencyObject
Public ReadOnly Property TemplatedParent As DependencyObject


元素的 FrameworkTemplateVisualTree 导致要创建此元素。The element whose FrameworkTemplateVisualTree caused this element to be created. 此值通常为 nullThis value is frequently null.


对于在应用程序标记或代码中创建的对象,TemplatedParent 经常 nullTemplatedParent is frequently null for objects that are created in your application markup or code. 这是因为你直接而不是通过模板创建这些对象。This is because you create those objects directly, not via a template. 通过从根遍历逻辑树或通过典型名称引用获取的对象引用不是来自模板。Object references obtained by walking the logical tree from the root, or by typical name references, do not come from a template.

TemplatedParent 可能不 null 的情况包括:命中测试、特定低级输入事件的事件处理、使用 VisualTreeHelper遍历可视化树或使用枚举器,这可能会返回来自模板的元素。Cases where TemplatedParent might not be null include operations such as hit-testing, event handling for certain low-level input events, walking the visual tree with VisualTreeHelper, or working with enumerators, which might return elements that came from templates. 另一种情况是,如果对现有 FrameworkTemplate 特别调用 FindName,并使用返回的对象。Another case is if you specifically call FindName against an existing FrameworkTemplate and are work with the returned object.

模板实际上是共享对象,模板的内容仅创建一次。Templates are actually shared objects, where the contents of the template are created only once. 因此,如果您获取对来自模板的元素的对象引用,则可能会发现明显的逻辑树不会到达页根。Therefore, if you obtain an object reference to an element that came from a template, you may find that the apparent logical tree does not reach to the page root. 为了将此类模板引用连接到页面的逻辑树,您应该获取 TemplatedParent 值,并根据需要继续导航该元素树。In order to connect such a template reference to the page's logical tree, you should get the TemplatedParent value and continue to navigate that element tree as desired.