Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 331
Maciek Avatar asked Aug 16 '09 21:08

Maciek


2 Answers

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.

like image 128
KeithMahoney Avatar answered Sep 18 '22 20:09

KeithMahoney


Each control with an x:Name has a field created for it in the partial class that gets created for the XAML. This field has an internal accessibility. Hence from code with in the "code-behind" cs (why do I hate that term?) you can simply use the control name directly in code to access it.

like image 21
AnthonyWJones Avatar answered Sep 18 '22 20:09

AnthonyWJones