未调用 Xamarin MessagingCenter 回调

Xamarin MessagingCenter callback not being called

我正在使用 Xamarin MessagingCenter 实现设备方向检测器。我想做的是将消息从 Android 项目中的 MainActivity 发送到我的 .NET Standart 项目中的 Singleton class 实现。

如您所见,我在 MainActivity 中覆盖了 "OnConfigurationChanged(...)" 方法,当我将方向从横向切换为纵向时,所有断点都在我的 IF 语句中命中。问题是我最近收到了这些消息。我的 "OrientationHelper" 中的回调是较新调用的。

"OrientationHelper" 在第一页加载时实例化(对于那些会说我没有实例的人:))

主要活动:

public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig)
{
    base.OnConfigurationChanged(newConfig);

    if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape)
        MessagingCenter.Send(this, "OrientationContract"
            , new OrientationChangedEventArgs(Orientation.Landscape));

    else if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait)
        MessagingCenter.Send(this, "OrientationContract"
            , new OrientationChangedEventArgs(Orientation.Portrait));
}

将从 MainActivity 接收消息的单例 class:

public class OrientationHelper
{
    private OrientationHelper()
        => MessagingCenter.Subscribe<OrientationChangedEventArgs>(this, "OrientationContract"
            , s => DeviceOrientation = s.Orientation);

    private static OrientationHelper s_instace;
    public static OrientationHelper Instance
    {
        get
        {
            if (s_instace == null)
                s_instace = new OrientationHelper();
            return s_instace;
        }
    }

    private Orientation _deviceOrientation;
    public Orientation DeviceOrientation
    {
        get => _deviceOrientation;
        private set
        {
            if (_deviceOrientation == value)
                return;
            _deviceOrientation = value;
        }
    }
}

OrientationChangedEventArgs:

public class OrientationChangedEventArgs : EventArgs
{
    public Orientation Orientation { get; private set; }

    public OrientationChangedEventArgs(Orientation orientation)
        => Orientation = orientation;
}

订阅和发送方法是这样定义的

  • Subscribe (object subscriber, string message, Action callback, TSender source = null)

  • Send (TSender sender, string message) Send (TSender sender, string message, TArgs args)

两个调用中的第一个 T 参数应与 class 发送消息的类型匹配

MessagingCenter.Send<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
        , new OrientationChangedEventArgs(Orientation.Landscape));

MessagingCenter.Subscribe<MyType, OrientationChangedEventArgs>(this, "OrientationContract"
        , s => DeviceOrientation = s.Orientation);