1

我是 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");
4

3 回答 3

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);
于 2010-12-09T14:04:40.763 回答
0

在这里http://www.silverlightshow.net/items/Implementing-Push-Notifications-in-Windows-Phone-7.aspx你会发现一个很好的例子,说明如何在 windows phone 7 上使用推送通知。

于 2010-12-09T14:00:55.460 回答
0

我很确定您可以通过创建一个单例来归档与 NSNotificationCenter 相同的结果,该单例包含一个可观察对象列表,该列表根据您的业务需求实现特定接口,或者调用一个兰巴,或触发一个事件,对于由此发送的每条消息单例你将交互观察列表并检查消息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!");
    }
 }
于 2014-08-27T18:14:09.190 回答