Reputation: 107
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 aSingleton
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?
Upvotes: 0
Views: 453
Reputation: 12179
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.
Upvotes: 1
Reputation: 6142
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://learn.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.
Upvotes: 0