Search code examples
c#xamarin.formsdata-bindingxamarin.android

Xamarin Forms Binding Label Text not working


I know that this had been answered multiple times before, and I've followed every possible guide. It doesn't work.

Here is my code:

XAML

<Label Text="{Binding Path=StatusMessage, Mode=TwoWay}"
       Margin="10,0,10,5"
       VerticalOptions="End"/>

C#

    private string statusMessage;
    public string StatusMessage { 
        get { return statusMessage; }
        set
        {
            statusMessage = value;
            OnPropertyChanged(nameof(StatusMessage));
        }
    }
    
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

The class extends INotifyPropertyChanged and to modify the label text I tried both StatusMessage = "Status: ..."; and Device.BeginInvokeOnMainThread(() => { StatusMessage = "Status: ...";});.

Nothing works.

Any idea how to fix this mess?

EDIT

Adding BindingContext = this; as suggested in the main helped.

Now it won't update the label from code called from a different thread, as follows

private void OnEnableUser(bool authenticated)
{
    if (SynchronizationContext.Current != null)
    {
        [...]
    } else
    {
        Device.BeginInvokeOnMainThread(() =>
        {
            OnEnableUser(authenticated);
        });
    }
}

Solution

  • Have you set the DataContext in the code behind?

    this.DataContext = classWithStatusMessage;