How to access a WPF control located in a ControlTemplate?

Abtin picture Abtin · May 4, 2009 · Viewed 27.1k times · Source

Usually, the WPF controls are declared in the .xaml files and not in the code behind (.xaml.cs files). However, sometimes I need to use some of those controls in code behind in order to manipulate them. How can I get the handle of such a control if it "resides" in the xaml file?

Answer

CSharper picture CSharper · May 4, 2009

You can use the FindName() method of the ControlTemplate class.

// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);