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?
Asked
Active
Viewed 2.9k times
2 Answers
34
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);

M. Jahedbozorgan
- 6,914
- 2
- 46
- 51
-
This was returning a null exception for me, then I realized something while trying some different answers here on SO : use CSharper's answer if the template you're looking in _is applied on myButton1_. But if myButton1 is just a member of the said template, use `(Grid)myButton1.FindName("grid");` instead (useful in button handlers). – Naucle Mar 09 '17 at 11:11
4
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".

Drew McGhie
- 1,086
- 1
- 12
- 26
-
FindName() kept returning null. FindResource() worked for my application. Thanks. – JohnForDummies Apr 28 '10 at 13:21