Issue
I am using Xamarin.Forms MVVM and sqlLite-net to make a Shared Mobile App.
I am getting an error bc 'AddRange' doesn't exist in ObservableCollection or I am using that function wrong.
All I want to do is to fill my ObservableCollection list. do I have to manually Add using loop? its weird ObservableCollection has a 'Add' method but no way to fill
Error: 'ObservableCollection' does not contain a definition for 'AddRange' and no accessible extension method 'AddRange' accepting a first argument of type 'ObservableCollection' could be found (are you missing a using directive or an assembly reference?)
using following refs:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using TestApp01_MVVM_Basic.Models;
using Xamarin.CommunityToolkit.ObjectModel;
using Xamarin.Forms;
using System.Collections.Specialized;
using TestApp01_MVVM_Basic.Services;
using System.Collections.Generic;
using System.Linq;
Below I am creating my ObservableCollection. I am getting my error on line: AddRange()
public ObservableCollection<ProductModel> ProductsList { get; set; }
public ProductViewModel()
{
ProductsList = new ObservableCollection<ProductModel>();
}
public async Task MyDisplayList()
{
var getData = ProductService.DisplayProduct();
ProductsList.AddRange(getData);
}
In Servies Class, I have following DisplayProduct() method. that returns a list from database
public static async Task<IEnumerable<ProductModel>> DisplayProduct()
{
await Init();
var GetProduct = await db.Table<ProductModel>().ToListAsync();
return GetProduct;
}
Solution
What you are looking for is implemented on Xamarin community toolkit package: ObservableRangeCollection which sub-class System.Collections.ObjectModel.ObservableCollection<T>
, you can use ObservableRangeCollection<ProductModel>
instead of ObservableCollection<ProductModel>
since the latter does not implement such method.
public ObservableRangeCollection<ProductModel> ProductsList { get; set; }
public ProductViewModel()
{
ProductsList = new ObservableRangeCollection<ProductModel>();
}
public async Task MyDisplayList()
{
var getData = await ProductService.DisplayProduct();
ProductsList.AddRange(getData);
}
public static async Task<IEnumerable<ProductModel>> DisplayProduct()
{
await Init();
var GetProduct = await db.Table<ProductModel>().ToListAsync();
return await Task.FromResult(GetProduct);
}
Answered By - Cfun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.