因此,使用 MessagingCenter 似乎是一种可行的方法。
遵循中的指导https://codemilltech.com/messing-with-xamarin-forms-messaging-center/
我创建了一个 MessagingMarker 类:
namespace TSDZ2Monitor.Classes;
public class MessagingMarker
{
}
就这样。
在我想从中发送对象的 ViewModel 中,我做了
MessagingCenter.Send(new MessagingMarker(), "BTDataUpdate", btd);
其中 btd 是我创建的用于保存数据的类的实例:这是一个简化的模型:
namespace TSDZ2Monitor.Models;
public partial class BluetoothData : ObservableObject
{
//Heart rate raw data
private int hRM;
public int HRM //heart rate
{
get => hRM;
set => SetProperty(ref hRM, value);
}
private double hRR; //heartrate R-R value
public double HRR
{
get => hRR;
set => SetProperty(ref hRR, value);
}
private double wheelRPM;
public double WheelRPM
{
get => wheelRPM;
set => SetProperty(ref wheelRPM, value);
}
private double cadence;
public double Cadence
{
get => cadence;
set => SetProperty(ref cadence, value);
}
}
在发送页面的 ViewModel 的构造函数中(可能最好在其他地方?)
public BluetoothData btd = new();
此 ViewModel 的 XAML 中未使用此值
在我接收的 ViewModel 中
我还创建了 BluetoothData 类的实例,但这在 XAML 绑定中使用
[ObservableProperty]
private BluetoothData bTData;
在 ViewModel 的构造函数中我有
BTData = new BluetoothData();
MessagingCenter.Subscribe<MessagingMarker, BluetoothData>(this, "BTDataUpdate", (sender, arg) =>
{
//Debug.WriteLine($"Message received {arg}");
BTData.HRM = arg.HRM;
BTData.HRR = arg.HRR;
BTData.WheelRPM = arg.WheelRPM;
BTData.Cadence = arg.Cadence;
});
好吧,它有效,不知道对性能的影响可能是什么,但它看起来反应相当灵敏。
按照我的想法,更理想的解决方案是创建任何 ViewModel 都可以访问的任何类的全局实例。