Maintaining the collection in a List/ObservableCollection

前端 未结 1 1079
野的像风
野的像风 2021-01-28 08:49

i have been successfully adding an item to list in a MVVM, and now my problem is maintaining the list in the view model. Every time i navigate to a page or go back to a page and

相关标签:
1条回答
  • 2021-01-28 09:29

    Here if your ViewModel is CartingDataSource in that case it is being instatiated on every page load. Now if that is the case, then you are creating a new instance of your collection in your constructor as below:

    public CartingDataSource() {
    
    
            CartData = new ObservableCollection<CartData>();
    
          }
    

    As a result of which it re-initializes your collection.

    You need to remove the initialization from your constructor and do something like this:

    public ObservableCollection<CartData> _cartData;
    
    public ObservableCollection<CartData> cartData
        {
    
         get {
                if(_cartData == null)
                {
                     _cartData = new ObservableCollection<CartData>();
                } 
             return _cartData;
             }
        set {
    
                _cartData = value;
           }
        }
    
    0 讨论(0)
提交回复
热议问题