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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With