Nyky
Nyky

Reputation: 13

How to set Label text in .net MAUI using M2MQTT from uPLibrary.Networking.M2Mqtt?

I am trying to set the text of a label with the message I get from MQTT. The message also arrives because I can output it in the debug console. I think it is a problem with the UI thread but I have no idea how to solve this problem. Here is the function which receives the data/message:

private async void client_MqttMsgPublishReceivedAsync(object sender, MqttMsgPublishEventArgs e)
{
    try
    {
        string msg = System.Text.Encoding.Default.GetString(e.Message);
        System.Diagnostics.Debug.WriteLine("Message Received: " + msg);

        await MainThread.InvokeOnMainThreadAsync(() =>
        {
            if (datenPage != null)
            {
                datenPage.UpdateContent(msg);
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("DatenPage is null.");
            }
        });
    }
    catch (Exception ex)
    {
        await DisplayAlert("MQTT", $"Error: {ex.Message}", "OK");
    }
}

this is the function which should set the label text:

public void UpdateContent(string newText)
{
    if (temp != null)
    {
        temp.Text = newText;
        System.Diagnostics.Debug.WriteLine($"Label changed to: {newText}");
    }
    else
    {
        System.Diagnostics.Debug.WriteLine("Label 'temp' is null.");
    }
}

Does anyone have an example of how to display a received MQTT message in a label? I expect the mqtt message to be displayed as the text of the label.

Upvotes: 1

Views: 109

Answers (1)

Bhavanesh N
Bhavanesh N

Reputation: 1255

I don't see any reason to use below to update the label text value.

await MainThread.InvokeOnMainThreadAsync(() => {}; 

In my personal experience

 MainThread.BeginInvokeOnMainThread(() => { });

have worked with Mqtt. Since the update needs to be on Uithread you can try few things.

1.) Use Dispatcher.Dispatch(() => { }); to update the text.


2.) Use Binding to set the Label text value. So that you can use OnPropertyChanged() to update view.

  <Label Text="{Binding MyLabelText}"/>

in xaml.cs

 private string _myLableText = string.Empty;
 public string MyLableText
 {
     get { return _myLableText; }
     set
     {
         _myLableText= value;
         OnPropertyChanged(MyLableText);
     }
 }

Make sure to set BindingContext = this;

Upvotes: 1

Related Questions