GetTemplateChild始终返回null

cod*_*rix 5 wpf wpf-controls

我正在使用GetTemplateChild,但它总是返回NULL.如何解决这个问题?

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))]
textPoints = (TextBlock)GetTemplateChild("TextBlock");
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 4

GetTemplateChild名称作为参数,而不是类型。由于您的 XAML 定义为:

<TextBlock Text="{Binding}" Foreground="Cyan" 
    x:Name="textPoints"
Run Code Online (Sandbox Code Playgroud)

尝试传递"textPoints"而不是"TextBlock"作为要检索的名称:

[TemplatePart(Name = "textPoints", Type = typeof(TextBlock))]
textPoints = (TextBlock)GetTemplateChild("textPoints");
Run Code Online (Sandbox Code Playgroud)