我正在尝试学习 MVVM Light 并将其用于我的 Windows Phone 8 应用程序。它工作得很好,但我找不到任何教程或示例如何使用带有 MVVM 模式的推送通知。
在我的 MainPage 中,我设置了 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 中找到了一些消息传递系统。我可以用它来通知吗?我应该使用哪些类型的消息?您能否给我一些示例代码或指向我的教程(文章/视频)。谢谢
最佳答案
我肯定会使用 MVVMlight 的消息传递系统,因为这为您提供了一个干净且松散耦合的回调,您的 View 模型可以订阅该回调。
在您的推送通知服务类中公开几个您的 View 模型可以监听的公共(public)消息字符串:
public static readonly string REFRESHCONTENTMESSAGE = "RefreshContent";
public static readonly string DELETECONTENTMESSAGE = "DeleteContent";
然后在您的 View 模型中订阅信使:
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;
如果您需要更深层次的定制,您可以编写自己的消息类型。但我认为你会处理现有的。这样做的好处是,您可以显式地仅监听您的特殊消息类型,如果您要发送大量消息,这将减少应用程序内部的消息流量。
关于c# - MVVM 灯 - 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28151341/