How to change label text in xamarin

Try initializing the Text value in XAML like the following:

<Label x:Name="YourLableName" Text="Initial Label"/>

Then access it in the code behind like the following:

YourLableName.Text = "Desired Name";

or

YourLableName.Text = variable;

Does this work in Xamarin?

Yes, it does.

If it does why does this code not change the text?

Because the Label component is not bounded to the variable, it just gets its value when you did Label_ControlSW.Text = controlSW_Out; and no furthermore.

To make it works you have basically two choices:

1. Set the value to the label on every change;

There's no magic here. Just set the values or variables like Ali Heikal's answer suggests, but you must do that every time manually.

2. Bind the page (View) to an Observable object (Model), then the view will listen to every change on your model and react to this (changing it's own Text value, for example).

I guess what you're intending to do is the second one. So you can create a public string property on your page's code-behind and bind the instance of your page to itself. Like this:

XAML

<Label Text="{Binding MyStringProperty}"
       .../>

Code behind

public partial class MyTestPage : ContentPage
{
    private string myStringProperty;
    public string MyStringProperty
    {
        get { return myStringProperty; }
        set 
        {
            myStringProperty = value;
            OnPropertyChanged(nameof(MyStringProperty)); // Notify that there was a change on this property
        }
    }
    
    public MyTestPage()
    {
        InitializeComponents();
        BindingContext = this;

        MyStringProperty = "New label text"; // It will be shown at your label
    }
}

You should take a look at official docs about data bindings and MVVM pattern on XF and if you're starting with Xamarin.Forms, I highly recommend you to follow the official getting started guide that addresses each topic clear and deep enough to learn everything you need.

I hope it helps.


In order to update the UI, you have to be on the UI thread. You would want to do something like:

 Device.BeginInvokeOnMainThread(() =>
 {
     Label_ControlSW.Text = controlSW_Out;
     Label_BLESW.Text     = bleSW_Out;
     Label_Mode.Text      = mode_Out;
 });

This will solve your problem, but as the others have stated in their answers, the Xamarin way to do this would be using data binding to update the view. The data binding will handle the UI update for you.