Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top