Accessing a control inside a ControlTemplate Accessing a control inside a ControlTemplate wpf wpf

Accessing a control inside a ControlTemplate


If you have overriden OnApplyTemplate then do not use FindResource() or Template.FindName() or any hacks with VisualTreeHelper. Just use this.GetTemplateChild("textBlock2");

Templates in WPF 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. Call the GetTemplateChild method to return references to objects that come from the template after it is instantiated. 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.

Check this link out:

http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.gettemplatechild.aspx

If your example is microsoft example then I suggest you to read it again. You might have skipped something.

http://msdn.microsoft.com/en-us/library/bb613586.aspx

To sum up - Use GetTemplateChild() when authoring custom control e.g. OnApplyTemplate, and use Template.FindName in other situations.


Your code is correct, but probably not in the right place... FindName will only work after the template has been applied. Typically, you use it when you override OnApplyTemplate in a custom control. Since you're not creating a custom control, you can do it in the Loaded event of the button.


Try the following code. This will return the templated element.

this.GetTemplateChild("ControlName");