2011-01-24 152 views
5

我正在使用GetTemplateChild,但它總是返回NULL。如何解決這個問題?GetTemplateChild總是返回空

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))] 
textPoints = (TextBlock)GetTemplateChild("TextBlock"); 
+0

你有沒有找到解決方案? _Reed Copsey_的答案對您提供的信息是正確的,但如果這仍然不起作用,那麼也許您可以發佈您的控件模板,因爲它可能包含錯誤。 – 2012-06-29 15:50:24

+1

根據我的經驗,在調用FrameworkElement.OnApplyTemplate()之前調用`FrameworkElement.GetTemplateChild()`是不安全的。嘗試子類化控件並重載`OnApplyTemplate()`。 – kevinarpe 2012-10-15 15:17:51

回答

4

GetTemplateChild名稱作爲參數,不類型。由於您的XAML定義爲:

<TextBlock Text="{Binding}" Foreground="Cyan" 
    x:Name="textPoints" 

嘗試通過"textPoints"代替"TextBlock"作爲名稱檢索:

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))] 
textPoints = (TextBlock)GetTemplateChild("textPoints"); 
+0

Thnaks,我試着用下面的代碼,我仍然得到相同的結果(即NULL)textPoints =(TextBlock)GetTemplateChild(「textPoints」);我錯過了一些瘦身? – codematrix 2011-01-24 19:21:35

2

貌似你試圖得到一些其他的控制模板的孩子,從那裏你正在調用GetTemplateChild?

如果您的ItemsControl位於某個UserControl內部,那麼GetTemplateChild將不起作用,因爲您的UserControl的子項不是模板子模塊的一部分,也不會遞歸搜索每個子模板的子模板。

大多數GetTemplateChild用於自定義控件中。