简体   繁体   中英

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);
        });
    }
}

Have you set the DataContext in the code behind?

this.DataContext = classWithStatusMessage;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM