0

我正在开发一个示例,其中消息中心将未从设备代码耦合到我的视图模型的状态消息发送。在这一点上,我在尝试查看模型之前使用了一条警报消息来通知事件。

为此,我在我的共享应用程序构造函数 (App.xaml) 中使用了一个静态视图实例,其中在视图构造函数中我为状态下标。

应用程序(共享)

public partial class App : Application
    {

        #region MasterDetailPage
        public static MasterDetailPage MDP;
        public static NavigationPage NAV = null;
        public static MainView _mainpage;
        #endregion

        public App ()
        {
            InitializeComponent();
            NAV = new NavigationPage(new StarterView()) { BarBackgroundColor = Color.FromHex("701424"), BarTextColor = Color.White }; ;
            MDP = new MasterDetailPage();
            MDP.BackgroundColor = Xamarin.Forms.Color.FromHex("701424");
            _mainpage = new MainView();
            MDP.Master = _mainpage;
            MDP.Detail = NAV;
            MainPage = MDP;
            MainPage.Title = "H2X";


        }

(查看共享)

public MainView ()
        {
            InitializeComponent ();

            string a="Test";
            #region MessegeCenter

            MessagingCenter.Subscribe<string,string>("APP", "Message_Received", async (sender,arg) => 
            {
                string b = a;
                a = $"{arg}";
                await DisplayAlert("Atenção", a+b, "Ok");
            });
            #endregion

        }

在特定平台代码(设备 - UWP)中,我创建了一个计时器,该计时器在主页构造函数中实例化一段时间后发送消息。

void dispatcherTimer_Tick(object sender, object e)
        {
            DateTimeOffset time = DateTimeOffset.Now;
            TimeSpan span = time - lastTime;
            lastTime = time;
            //Time since last tick should be very very close to Interval
            TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
            timesTicked++;
            if (timesTicked > timesToTick)
            {                   
                MessagingCenter.Send<string,string>("APP","Message_Received","MR");
            }
        }

当我运行它时,会打开两次具有相同文本的警报消息,但没有两个订阅。相同的文本向我提供了来自相同发送事件的信息。

问题出在哪里 ?与我的静态视图有什么关系吗?

先感谢您

吉尔赫姆

4

1 回答 1

0

始终取消订阅 MessagingCenter 是一种很好的做法。

MessagingCenter.Unsubscribe<string, string>(this, "Message_Received");

如果 MessagingCenter 被订阅了两次,那么函数将被调用两次。

于 2020-07-24T09:40:58.950 回答