Xamarin MessagingCenter回调未被调用

时间:2019-02-13 13:55:57

标签: c# android .net xamarin messagingcenter

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

如您所见,当我将方向从横向切换为纵向时,我在MainActivity中重写了“ OnConfigurationChanged(...)”方法,并且在IF语句中击中了所有断点。问题是我较新时收到这些消息。我的“ OrientationHelper”中的回调是较新的名称。

在首页加载时会显示“ OrientationHelper”(对于那些会说我没有实例的人:))

MainActivity:

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接收消息的单一类:

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

1 个答案:

答案 0 :(得分:0)

subscribe和send方法的定义如下

  
      
  • 订阅(对象订阅者,字符串消息,操作回调,TSender源= null)

  •   
  • 发送(TSender发送者,字符串消息)发送(TSender发送者,字符串消息,TArgs参数)

  •   

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

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

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