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.
CodePudding user response:
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.
Hope this helps good luck !
CodePudding user response:
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.
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.