MVVM轻推 - 推送通知

时间:2015-01-26 13:49:43

标签: c# windows-phone-8 mvvm push-notification mvvm-light

我正在尝试学习MVVM Light并将其用于我的Windows Phone 8应用程序。它运行良好,但我找不到任何教程或示例如何使用推送通知与MVVM模式。

在我的主页中,我设置了HttpNotificationChannel,我收到了通知:

void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
        {
            StringBuilder message = new StringBuilder();
            string relativeUri = string.Empty;

            message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());

            // Parse out the information that was part of the message.
            foreach (string key in e.Collection.Keys)
            {
                message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);

                if (string.Compare(
                    key,
                    "wp:Param",
                    System.Globalization.CultureInfo.InvariantCulture,
                    System.Globalization.CompareOptions.IgnoreCase) == 0)
                {
                    relativeUri = e.Collection[key];
                }
            }

            // Display a dialog of all the fields in the toast.
            //Dispatcher.BeginInvoke(() => MessageBox.Show(message.ToString()));

        }

现在我不知道该怎么做。我会收到大约5种不同类型的通知,它们应该将应用程序导航到应用程序或刷新页面中的不同页面(或者可能将一些数据保存到存储中)。我怎样才能做到这一点?当我在搜索时,我在mvvm light中找到了一些消息系统。我可以用它来通知吗?我应该使用哪些类型的消息?你能给我一些示例代码或指向我的教程(文章/视频)。感谢

1 个答案:

答案 0 :(得分:2)

我肯定会使用MVVMlight的消息传递系统,因为这会为您提供一个视图模型可以订阅的干净且无法耦合的回调。

在推送通知服务类中,公开了一些您的viewmodel可以监听的公共消息字符串:

public static readonly string REFRESHCONTENTMESSAGE = "RefreshContent";
public static readonly string DELETECONTENTMESSAGE = "DeleteContent";

然后订阅viewmodel中的messenger:

Messenger.Default.Register<NotificationMessage>(this, HandleMessage);

最后设置处理程序:

public void HandleMessage(NotificationMessage message) {
    if (message.Notification.Equals(YourService.REFRESHCONTENTMESSAGE))
    {
        // Do stuff like navigating to a page.
    }
    else if (message.Notification.Equals(YourService.DELETECONTENTMESSAGE))
    {
        // Do something else.
    }
}

现在,您只需在收到新通知时从推送通知服务类发送消息:

Messenger.Default.Send<NotificationMessage>(new NotificationMessage(REFRESHCONTENTMESSAGE));

这只是一个简短的版本。如果您正在寻找一个可以实际携带数据的版本,请转到包含内容的NotificationMessage(并使用通用方面调整上面的代码):

Messenger.Default.Send<NotificationMessage<MyObject>>(new NotificationMessage<MyObject>(REFRESHCONTENTMESSAGE));

// In your handler:
MyObject payload = message.Content;

如果您需要更深层次的自定义,您可以编写自己的消息类型。但我认为你会对现有的做得好。优点是您可以显式地只监听您的特殊消息类型,如果您要发送大量关键消息,这将减少应用程序内的消息流量。