Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the name of a Label in Xamarin Forms

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
            }
        };
    }
}
like image 739
Bob The Janitor Avatar asked Jul 16 '14 23:07

Bob The Janitor


2 Answers

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

like image 96
IdoT Avatar answered Sep 18 '22 13:09

IdoT


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;
like image 22
qfactor77 Avatar answered Sep 22 '22 13:09

qfactor77