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.