Windows Phone 7相当于NSNotificationCenter?

时间:2010-12-09 13:22:50

标签: iphone windows-phone-7 mvvm-light messages nsnotificationcenter

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

我想做什么:

  • 注册到Notification-Id并在收到Notification-Id时执行某些操作
  • 使用Notification-Id和上下文(传递给观察者的对象)发送通知
  • 将通知注册到相同Notification-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");

3 个答案:

答案 0 :(得分:4)

以下是如何处理MVVM Light Toolkit:

注册:

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

发送:

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

答案 1 :(得分:0)

在这里http://www.silverlightshow.net/items/Implementing-Push-Notifications-in-Windows-Phone-7.aspx,您将找到一个关于如何在Windows Phone 7上使用推送通知的一个很好的示例。

答案 2 :(得分:0)

我非常确定您通过创建一个单例来存档与NSNotificationCenter相同的结果,该单例包含一个基于您的业务需求实现特定接口的可观察对象列表,或者为每条消息调用lamba或触发事件通过这个单例发送,你将整理可观察的列表并检查消息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!");
    }
 }