How to share an instance of a class between all xamarin pages?

I am starting in Xamarin and I am stuck.

I have 3 different pages, how can I share an instance of a class with all of them?

eg:

//I have this class instance in the first page
Person p = new Person("Jack");

//And I'd like to get the content in all pages
string name = p.getName();

      

Can we do this without passing the instance in parameters?

thank

+3


source to share


2 answers


The easiest way is to assign and access it from your class Xamarin.Forms

Application

:

public class App : Application
{
    public MySharedClass MySharedObject;
    ~~~
}

      



Then, from any of your other pages, you can access the current one Application

:

var obj = (Application.Current as App).MySharedObject;

      

+5


source


I usually create a service that will return a value / instance for my clients (i.e. pages / views).

I usually insert this service as a constructor argument for all my pages or view models that require this value.

As a result, there was a ceremony related to the strategy that I defined. The advantage, however, is that the technique I describe is a verifiable unit. Hence, writing tested code (aka: testable) saves time in the long run.



Just remember that adding a property to the App class is quick and messy. However, it is not verifiable. Hence, a unit test does not require running the entire application instance to test a piece of business logic.

Another option is to inject a dictionary into your pages / views. Your dictionary can even be static to avoid ceremony in your application logic. However, this will affect your unit tests if you don't clear the dictionary after each test run.

In conclusion, I recommend creating a custom service or dictionary. Just keep in mind that if you are using a dictionary that is statically declared, then your unit tests must clear the dictionary at the break stage, otherwise your other tests will be affected depending on the side effect of the previously run tests.

+4


source







All Articles