I want to create calculator with history and I need to share data between history page and calculating page.
I know about two ways of sharing data between pages in MAUI.
- Passing data in parameter of
Shell.Current.GoToAsync();
- Saving data to
.txt
file and read from it when class initializes
But in my case first way would redirect me everytime I calculate something and second one seems way to bloated to me. Is there any simpler way to share data?
CodePudding user response:
Following up on my thinking... I've done this is Xamarin.Forms
but it can transfer to .net MAUI
I'm confident. This is just an example so the properties are definitely are not correct
First thing you do is create an Interface
that you can speak to.
public interface ICalculatorData
{
//Here you add all he properties that you want to have. What ever you store in the .txt
//transfer them here and make them into properties
List<double> Inputs { get; set; }
List<string> Operators { get; set; }
double Answer { get; set; }
}
Then create a class which consumes that Interface
public class CalculatorData : ICalculatorData
{
//Implementing the interface here.
public List<double> Inputs { get; set; } = new List<double>();
public List<string> Operators { get; set; } = new List<string>();
public double Answer { get; set; } = 0.0;
}
In you entry class of .net MAUI
create a DependencyService
. Use the link above I've sent to change the code to work for you.
public App()
{
InitializeComponent();
//Creating a singleton of that class
DependencyService.Register<ICalculatorData, CalculatorData>();
MainPage = new AppShell();
}
I don't know how you implement your Calculator class but this is how you can access that singleton instance and have the data persistent as long as the app is running.
public class Calculator
{
//You can now have a singleton at your disposal at any point allowing you to access all of its properties with the set values
ICalculatorData CalculatorData = DependencyService.Get<ICalculatorData>();
//Your code for the calculator...
}
You can have as many ICalculatorData CalculatorData = DependencyService.Get<ICalculatorData>();
as you want and with any class.
If you want to go a step further you can create a class for all your ViewModels
to inherit from BaseClass
I believe it comes with Shell App
anyways. You can create that there and have any ViewModel
have access to it without having that extra line of code in all your classes, I personally do this to have persistent data I want to have access to at all times during the runtime of the application.
With this you no longer need to pass data around Shell App
and just use that Singleton. You can now have some code to tell your Save()
method to save on Answer PropertyChanged
and write it to a file.
Hope this helps. Please ask more question if needed in the comments I can do some research into .net MAUI
if you get stuck.