AgentRed
AgentRed

Reputation: 72

Xamarin Forms - Singleton with a List

Can somebody help me implement a singleton with a list from Carting module.

My error: 'Cart' does not contain a definition for 'Add' and the best extension method overload 'SettersExtensions.Add(IList, BindableProperty, object)' requires a receiver of type 'IList'

here's what i have for now

Cart.cs

public sealed class Cart
    {
        public static Cart Instance { get; } = new Cart();

        static Cart() { } 
        private Cart() { }

        public void GetAddedMeals()
        {

        }
    }

QuantityPopUp.xaml.cs

private void btnOK_Clicked(object sender, EventArgs e)
        {


            Cart.Instance.Add(tempcodeofmenu, int.Parse(entQuantity.Text));


            Navigation.PushAsync(new OrderCart());



        }

OrderCart.cs

  public OrderCart ()
        {
            InitializeComponent ();

          MyCart.ItemsSource = Cart.Instance.GetAddedMeals();
        }

Upvotes: 0

Views: 348

Answers (1)

noelicus
noelicus

Reputation: 15055

You need to return something from:

public ObservableCollection<YourItemClass> GetAddedMeals()
{
    ... // Fill in the blanks according to your implementation. Return a collection.
}

An ObservableCollection can be useful as a source for your list for monitoring changes to that list.

And then you need to allow this to be added to. Perhaps you meant Cart to have a collection as a base class? That way an "Add" may be implemented that way?

public Cart : ObservableCollection<YourItemClass>

But considering your question I'd avoid that for now and go straight for your Cart class owning an ObservableCollection as a member:

private ObservableCollection<YourItemClass> myCollection;

And implement your own Add class:

public void Add(YourItemClass item)
{
    myCollection.Add(item);
}

Upvotes: 1

Related Questions