简体   繁体   中英

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();
        }

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM