Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share a class instance between all xamarin pages?

I am starting in Xamarin, and I am stuck.

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

for example:

//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 that without passing the instance in parameters ?

Thanks

like image 692
NoteStylet Avatar asked Dec 19 '22 08:12

NoteStylet


2 Answers

The easiest way is to assign and access it from your Xamarin.Forms Application class/instance:

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

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

var obj = (Application.Current as App).MySharedObject;
like image 101
SushiHangover Avatar answered Feb 19 '23 12:02

SushiHangover


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

I usually inject this service as a constructor argument for all my pages or viewmodels that require that value.

As a result, there's some ceremony that's involved with the strategy that I identified. However, the advantage is that the technique that I described is unit testable. Hence writing proven (aka: testable) code saves time in the long run.

Just note that adding a property to the App class is quick and dirty. However, it does not lend itself well to testability. Hence, a unit test should not require launching an entire application instance to validate a slice of business logic.

Another option is to inject a dictionary into your pages/viewmodels. Your dictionary can even be static to avoid ceremony within your application logic. However, this will affect your unit tests if you do not clear the dictionary after every test run.

In conclusion, I recommend creating an arbitrary service or a dictionary. Just note that if you use a dictionary that's statically declared then your unit tests must clear out the dictionary on the teardown stage or else your other tests will be affected based on the side effect of previously ran tests.

like image 30
Scott Nimrod Avatar answered Feb 19 '23 14:02

Scott Nimrod