I'm trying to add a name to a label so I can find it using the Content.FindByName<>() method
as far as I can tell the Xamarin.Forms.Label() class doesn't have a Name property
Here is my page class
public class HelloWordCodePage : ContentPage
{
public Label HelloWorldLabel;
public HelloWordCodePage()
{
HelloWorldLabel = new Label{Text = "Hello World", };
ConstructView();
}
public void ConstructView()
{
Content = new StackLayout
{
Children =
{
HelloWorldLabel
}
};
}
}
If you define your label in Xaml, you can use this syntex:
<Label x:Name="YourLableName" Text="A simple Label" />
And then access it in the code behind like this
YourLableName.Text = "bla bla"
However, if you don't use Xaml, and all your page definition is found in the code behind, you should keep a reference to that label in order to access it instead of finding it using Content.FindByName<>()
as @Sten Petrov commented
As IdoT says, if you define an object at runtime, you need to keep a reference to that in order to access it as it is not possible to assign a name. I use a dictionary like this:
Dictionary<Guid, String> ControlsDictionary = new Dictionary<Guid, string>();
Then when I create an object:
Button bt = new Button {Text="Yay!"};
bt.Clicked += OnButtonClicked;
StackLayout.Children.Add(bt);
ControlsDictionary.Add(bt.Id, "myname");
In the Click event handler I can identify the sender "name":
async void OnButtonClicked(object sender, EventArgs args)
{
Button btn = (Button)sender;
String NameofButton = ControlsDictionary[btn.Id];
}
also you can obtain the Id from the "name":
Guid IdfromName = ControlsDictionary.First(x => x.Value == "myname").Key;
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