Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetTemplateChild always returns null

I am using GetTemplateChild as follow, but it always returns NULL. How to fix this?

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))]
textPoints = (TextBlock)GetTemplateChild("TextBlock");
like image 770
codematrix Avatar asked Jan 24 '11 19:01

codematrix


2 Answers

GetTemplateChild takes the name as a parameter, not the type. Since your XAML is defined as:

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

Try passing "textPoints" instead of "TextBlock" as the name to retrieve:

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))]
textPoints = (TextBlock)GetTemplateChild("textPoints");
like image 186
Reed Copsey Avatar answered Nov 04 '22 06:11

Reed Copsey


Looks like you are trying to get template child of some other control, from where you are calling GetTemplateChild?

If your ItemsControl is inside some UserControl then GetTemplateChild will not work as children of your UserControl are not part of template child anyway and it will not recursively search every child's template child.

Mostly GetTemplateChild is used in Custom Controls.

like image 2
Akash Kava Avatar answered Nov 04 '22 06:11

Akash Kava