Xamarin NSNotificatioCenter:我怎样才能通过NSObject?

我正在尝试使用NSNotificationCenter在我的应用程序中向另一个应用程序发布通知。 所以在我的目标类中,我创建我的观察者如下:

NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", delegate {ChangeLeftSide(null);}); 

我有我的方法:

 public void ChangeLeftSide (UIViewController vc) { Console.WriteLine ("Change left side is being called"); } 

现在从另一个UIViewController我发布通知如下:

 NSNotificationCenter.DefaultCenter.PostNotificationName("ChangeLeftSide", this); 

如何在目标类中访问在post通知中传递的视图控制器? 在iOS中它非常直接,但我似乎无法找到单声道(Xamarin)…

当您使用AddObserver ,您希望以稍微不同的方式执行此操作。 请尝试以下方法:

 NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide); 

并声明您的ChangeLeftSide方法符合AddObserver期望的Action – 为您提供实际的NSNotification对象。 :

 public void ChangeLeftSide(NSNotification notification) { Console.WriteLine("Change left side is being called by " + notification.Object.ToString()); } 

因此,当您使用PostNotificationName ,您将UIViewController对象附加到通知,该通知可以通过Object属性在NSNotification检索。

我找到了答案,以下是我在问题中发布的代码需要进行的更改:

 public void ChangeLeftSide (NSNotification notification) { Console.WriteLine ("Change left side is being called"); NSObject myObject = notification.Object; // here you can do whatever operation you need to do on the object } 

并且观察者被创建:

 NSNotificationCenter.DefaultCenter.AddObserver ("ChangeLeftSide", ChangeLeftSide); 

现在你可以投射或输入检查NSObject并用它做任何事情! 完成!