How to access a WPF control located in a ControlTemplate? How to access a WPF control located in a ControlTemplate? wpf wpf

How to access a WPF control located in a ControlTemplate?


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

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


I'm unsure about what you're asking, so I'll try and answer both instances that I'm interpreting as your question.

1)If you want to declare an explicit control, and then edit it directly, all you have to do is set the name property like such:

<Canvas x:Name="myCanvas"/>

You can then access the canvas through the Name as such:

myCanvas.Background = Brushes.Blue;

2)If you're looking to declare a generic control, and then use it multiple times, you can do it like this:

<Window>   <Window.Resources>      <Ellipse x:Key="myEllipse" Height="10" Width="10">   </Window.Resources></Window>

You can then access that predefined control using this syntax in code:

Ellipse tempEllipse = (Ellipse)FindResource("MyEllipse");

If you want to use the Resourse as a template for multiple controls, add x:Shared="false".