I need to create the control in the class code, not in Xaml. I create the control as follows:
Button button = new Button
{
Text = "Click to Rotate Text!",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
My question is, how do I assign a name to the control as you would in Xaml with x:Name?
I tried with all properties but there is no adequate one.
The XAML x:Name maps to the element's StyleId property. So, for example, to set the name to "MyButton":
Button button = new Button
{
StyleId = "MyButton",
Text = "Click to Rotate Text!",
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.Center
};
From the Element.StyleId docs:
Gets or sets a user defined value to uniquely identify the element.
See also: https://learn.microsoft.com/answers/questions/939731/can-styleid-property-be-used-reliably-to-access-xa.html
Depending on your needs, you may or may not still need to assign the control to a custom field, as shown in FrekyAli's answer.
When you create a XAML and use the x:Name attribute for a control it basically creates a private field for your control in the xaml.g.cs (Autogenerated).
Something like this would be a replica:
private readonly Button buttonName;
public YourPage()
{
buttonName = new Button();
this.Content= buttonName;
}
of this XAML
<ContentPage>
<Button x:Name="buttonName"/>
</ContentPage>
Obviously this is simplified for readability.
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