FrameworkElement.GetTemplateChild(String) 方法


返回实例化的 ControlTemplate 可视化树中的命名元素。Returns the named element in the visual tree of an instantiated ControlTemplate.

protected public:
 System::Windows::DependencyObject ^ GetTemplateChild(System::String ^ childName);
protected internal System.Windows.DependencyObject GetTemplateChild (string childName);
member this.GetTemplateChild : string -> System.Windows.DependencyObject
Protected Friend Function GetTemplateChild (childName As String) As DependencyObject



要查找的子级的名称。Name of the child to find.



请求的元素。The requested element. 如果具有所请求名称的元素不存在,则可以为 nullMay be null if no element of the requested name exists.


WPFWPF 中的模板具有独立的名称范围。Templates in WPFWPF have a self-contained namescope. 这是因为模板是重复使用的,当控件的多个实例实例化其模板时,模板中定义的任何名称都不能保持唯一。This is because templates are re-used, and any name defined in a template cannot remain unique when multiple instances of a control each instantiate its template. 调用 GetTemplateChild 方法,以返回对实例化后来自模板的对象的引用。Call the GetTemplateChild method to return references to objects that come from the template after it is instantiated. 不能使用 FrameworkElement.FindName 方法来查找模板中的项,因为 FrameworkElement.FindName 在更通用的作用域中操作,并且在应用了 ControlTemplate 类本身与实例化模板之间没有任何连接。You cannot use the FrameworkElement.FindName method to find items from templates because FrameworkElement.FindName acts in a more general scope, and there is no connection between the ControlTemplate class itself and the instantiated template once it is applied.

FrameworkTemplate.FindName 提供与此方法相同的函数。FrameworkTemplate.FindName supplies the same function as this method. FrameworkTemplate.FindName 是公共的,而不是受保护的,它将使用正确的名称范围注意事项,使其能够访问元素中的模板,并查找其中的已命名项。FrameworkTemplate.FindName is public instead of protected, and it uses correct name-scoping considerations that allow it to access the template within an element and find named items within it. 如果需要在其父控件之外获取元素,请使用 FrameworkTemplate.FindNameUse FrameworkTemplate.FindName when you need to get an element outside of its parent control.