I have a Xamarin.Android and Xamarin.iOS app. The app has a data model called as PRODUCT. In various screens, we will list the products depending on queries or other criteria. Let's say that the user navigated from Activity-A (ViewController in ios) to Activity-B and further into C, D etc by selecting a specific product. Based upon the user interaction in Activity-D I need to update UI in all the other activities while navigating back from D to A . How can I propagate the changes down the back stack or how to update the UI accordingly while navigating back. The certain activity might contain the UI element directly in it while at other places its part of a list. The product will have a unique id.
Solution:
For Xamarin.iOS:
There are several ways to pass data between ViewControllers. Here I recommend you to use NSNotificationCenter
in your case. For example, if you want to change A,B,C's
UI when you do some specify action in D
, you can use the code below:
In the controller D
: post a Notification
in your specify action,you can add your personal requirments(for example:product ID, UI style) in dictionary(the third parameter):
NSNotificationCenter.DefaultCenter.PostNotificationName("changeUI",null, new NSDictionary("key1", 1, "key2", 2));
In the controller A,B,C
, register as the observer of the Notification
which named changeUI
.
NSObject notificationToken;
void Setup()
{
notificationToken = NSNotificationCenter.DefaultCenter.AddObserver((NSString)"changeUI", doChangeUI);
}
void doChangeUI(NSNotification notification)
{
NSDictionary dict = notification.UserInfo;
Console.WriteLine("changeUI");
}
void Teardown()
{
NSNotificationCenter.DefaultCenter.RemoveObserver(notificationToken);
}
So, once the controller D
post a Notification
named changeUI
, all the observer will receive the Notification
and perform the function predefined(Here is doChangeUI
). You can get your personal requirments in the dict
(notification.UserInfo
) and update UI in the controllers.
You can refer: NSNotificationCenter
For Xamarin.Android:
You can use Broadcast-Receivers
in Xamarin.Android. It's almost same as NSNotificationCenter in Xamarin.iOS.
1.Creating a Broadcast Receiver
in Activity A,B,C
;
2.Publishing a Broadcast
in Activity D
;
3.Do your stuff when you received the broadcast
You can refer to the document for more detail:broadcast-receivers