Home > other >  public variable in App class can't get referenced in other class xamarin forms
public variable in App class can't get referenced in other class xamarin forms

Time:05-10

I have this as my App.xaml.cs

using System;
using System.Collections.Generic;
using Xamarin.Forms;
using System.Threading.Tasks;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json;
using System.Net.Http;

namespace MyShop
{
    public partial class App : Application
    {
        public string productsJSON = {{very large string}};
        public List<Product> jsonDataCollection = new List<Product>();
        public App()
        {
            InitializeComponent();
            
            jsonDataCollection = JsonConvert.DeserializeObject<List<Product>>(productsJSON);
            foreach (Product p in jsonDataCollection)
            { 
                Application.Current.Properties[p.Id] = 0;
            }

            MainPage = new NavigationPage(new Page1());
        }
 ...

In my ProductsPage.xaml.cs, I want to reference the public variable productsJSON so I call it as App.productsJSON and assigned to a string variable productsJSON.

using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Newtonsoft.Json;
using System.Net.Http;

namespace MyShop
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ProductsPage : ContentPage
    {
        public ProductsPage(string title)
        {
            InitializeComponent();
            Title = title;

            string productsJSON = App.productsJSON;

            displayProducts(productsJSON);
        }
    ...

For that, I get the error: CS0120: An object reference is required for the non-static field, method, or property 'App.productsJSON'

I'm confused because from the solutions online when referencing a property from another class, you just call the class then dot, and then the property name. I don't quite get the object reference error and it didn't work when I casted it to string like <string>App.productsJSON

CodePudding user response:

you need a reference to the instance of the App class in order to access a non-static field or property

var json = ((App)Application.Current).productsJSON;
  • Related