简体   繁体   中英

How to keep shared data without using singleton in Xamarin.forms

I have a ContentPage with a ListView . I'm navigating to this content page using another content page's button. This button shows the list item count. I have ViewModel connected to each content page. I can update the count when add items to my ObservableCollection since field is adding not from the list page. But when I delete an item from the list view, I want to update the count in that time as well. How can I keep this ObservableCollection as a shared one between these 2 ContentPAges ? I know using a Singleton class we can do this. But since my code should support for unit testing it seems I cannot do this.

What is the best way to make this ObservableCollection shared among these content pages?

If I understand correctly you need a single data repository to be shared between multiple ViewModels . Which means that you need to keep a single instance of the repository somewhere in your code base. Depends on your project setup this repository can live in the IOC container or as a simple property within the App class or elsewhere. Also, depends on the collection data type you also may need to persist the data to SQL, local storage or etc. This way it will be trivial to access the collection from any ViewModel in the application.

However, since I don't understand your intents fully, there might be other solutions. Like passing the reference of the collection to the next page and etc.

If the only information you are wanting to share is the actual count of the items in the list, you could use the MessagingService that is build in in Xamarin Forms.

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/messaging-center

So in your example maybe create a class that holds all the info that you want to share and in one page do a

MessagingCenter.Send<ShareInfo>(...)

So you can pass data.

And in the other page do

MessagingCenter.Subscribe<ShareInfo>(...)

To receive the data and use that to update the button count.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM