Silverlight 3.0 : How do I get grid children by x:Name?

Maciek picture Maciek · Aug 16, 2009 · Viewed 9.1k times · Source

Let's assume that I've got XAML representing a Grid with some children in it, each child is a different control, with a x:Name. How do I "get" those controls from code by name ?

Answer

KeithMahoney picture KeithMahoney · Aug 17, 2009

If the code that you are writing is in the code-behind file for the xaml file, then Visual Studio should automatically generate member variables containing references to any named elements in the xaml file. So if you have a Button with x:Name="myButton", you can access this button via this.myButton.

If you want to reference a named element from somewhere other than the code-behind file, you can call FindName on the element to the named element, e.g.:

Button myButton = myGrid.FindName("myButton") as Button;

where myGrid is a reference to the Grid in question.