我是WP7的新手,来自iPhone开发。在iPhone上,我用来使用nsnotificationcenter通知我的程序。 NSNotificationCenter正在开箱即用的框架。 WP7中有类似的东西吗?我偶然发现了Uppon MVVM-Light工具包,但我不确定如何正确使用它。

我想做的事:

  • 注册通知ID并在收到通知ID时做某事
  • 带有通知-ID和上下文的通知(对象传递给观察者)
  • 注册相同通知的每个人都将收到通知

所以类似:注册

NotificationCenter.Default.register(receiver, notification-id, delegate);

发送:

NotificationCenter.Default.send(notification-id, context);

注册的示例:

NotificationCenter.Default.register(this, NotifyEnum.SayHello, m => Console.WriteLine("hello world with context: " + m.Context));

发送...

NotificationCenter.Default.send(NotifyEnum.SayHello, "stackoverflow context");
有帮助吗?

解决方案

这是使用MVVM轻型工具包的方法:

注册:

Messenger.Default.Register<string>(this, NotificationId, m => Console.WriteLine("hello world with context: " + m.Context));

发送:

Messenger.Default.Send<string>("My message", NotificationId);

其他提示

这里 http://www.silverlightshow.net/items/implementing-push-notifications-in-windows-phone-phone-7.aspx 您将找到一个很好的示例,说明如何在Windows Phone 7上使用推送通知。

我很确定您通过创建一个单身人士来存储与NSNotificationCenter相同的结果,该单元列有一个可观察到的列表,该列表可根据您的商务要求或致电lamba或触发事件,以实现特定接口Singleton您将与可观察到的列表交叉并检查消息ID,一旦找到一个或多个,就可以调用接口方法,或执行lambda表达式或触发已定义的事件以消化消息内容。

如下所示:

public class NotificationCenter {

    public static NotificationCenter Default = new NotificationCenter();

    private List<KeyValuePair<string, INotifiable>> consumers;

    private NotificationCenter () {

       consumers = new List<INotifiable>();
    }

    public void Register(string id, INotifiable consumer) {

        consumers.Add(new KeyValuePair(id, consumer));
    }

    public void Send(String id, object data) {

        foreach(KeyValuePair consumer : consumers) {

            if(consumer.Key == id)
                consumer.Value.Notify(data);
        } 
    }
 }

 public interface INotifiable {

    void Notify(object data);
 }


 public class ConsumerPage  : PhoneApplicationPage, INotifiable {

    public ConsumerPage() {

       NotificationCenter.Default.Register("event", this);
    }

    private Notify(object data) {

       //do what you want
    }
 }

 public class OtherPage : PhoneApplicationPage {

    public OtherPage() {

        NotificationCenter.Default.Send("event", "Hello!");
    }
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top