2011-01-24 158 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用于自定义控件中。