如何使用 uPLibrary.Networking.M2Mqtt 中的 M2MQTT 在 .net MAUI 中设置标签文本?

问题描述 投票:0回答:1

我正在尝试使用从 MQTT 收到的消息设置标签文本。该消息也会到达,因为我可以在调试控制台中输出它。我认为这是 UI 线程的问题,但我不知道如何解决这个问题。 这是接收数据/消息的函数:

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

这是应该设置标签文本的函数:

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

有人有如何在标签中显示收到的 MQTT 消息的示例吗? 我希望 mqtt 消息显示为标签的文本。

c# .net maui mqtt ui-thread
1个回答
0
投票

我看不出有任何理由使用下面的方法来更新标签文本值。

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

以我个人的经历

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

曾与 Mqtt 合作过。由于更新需要在 Uithread 上进行,因此您可以尝试一些操作。

1.) 使用

  Dispatcher.Dispatch(() => { });
更新文本。


2.) 使用 Binding 设置 Label 文本值。这样你就可以使用OnPropertyChanged()来更新视图。

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

在 xaml.cs 中

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

确保设置 BindingContext = this;

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.