tags:

views:

1014

answers:

3

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?

+2  A: 

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
+1  A: 

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
FindName() kept returning null. FindResource() worked for my application. Thanks.
JohnForDummies
A: 

How I can access to wpf methods from javascript???

Rybka