views:

1076

answers:

2

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 ?

+1  A: 

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.

AnthonyWJones
Would you be so kind and elaborate that?
Maciek
I think he means, if you have x:Name="MyNamedControl". Once you compile it, the Reference.g file will automatically have it availble so you can just type this.MyNamedControl
Paully
But if you are doing templating, this won't happen and you should use FindName
Paully
+2  A: 

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.

KeithMahoney
woot! this works. I found an alternative which is a bit more complex but works as well :private Button myButtnon;foreach(FrameWorkElement fe in myGrid.Children){ if(fe.GetType() == typeof(Button) myButton = fe as Button;}
Maciek
Note that myButton would be a field with internal accessibility hence even from code outside the code-behind file you can access it without resorting to FindName.
AnthonyWJones