我正在尝试从我的xamarin表单应用程序的firebase过滤数据。
这是我的列表视图在。xaml页面的代码
<ListView x:Name="listView" ItemsSource="{Binding ProductList}" HasUnevenRows="true" SeparatorVisibility="None" BackgroundColor="#fafafa">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Margin="0,0,0,40">
<Label Text="{Binding Name}" FontSize="Large" TextColor="Black"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在cs文件的xaml页面,我有内部构造函数:
BindingContext = new ProductsViewModel(userId, Navigation, productType);
这是我的ViewModel
public class ProductsViewModel : BaseViewModel
{
public Guid UserId { get; set; }
public string ProductType { get; set; }
private APIService services;
public INavigation Navigation { get; }
private ObservableCollection<ProductModel> _ProductList = new ObservableCollection<ProductModel>();
public ObservableCollection<ProductModel> ProductList
{
get { return _ProductList; }
set
{
_ProductList = value;
OnPropertyChanged();
}
}
public ProductsViewModel(Guid userId, INavigation navigation, string productTyp)
{
UserId = userId;
ProductType = productTyp;
services = new APIService();
Navigation = navigation;
ProductList = services.GetProducts();
}
}
和APIService的类
internal ObservableCollection<ProductModel> GetProducts()
{
var outfitFeedData = firebase
.Child("Products")
.AsObservable<ProductModel>()
.AsObservableCollection();
return outfitFeedData;
}
所有工作正常,直到我开始查询结果,然后我开始得到转换类型异常。
,
internal ObservableCollection<ProductModel> GetProducts()
{
var outfitFeedData = firebase
.Child("Products")
.AsObservable<ProductModel>()
.AsObservableCollection().Select(item => new ProductModel
{
Type = "K",
});
return outfitFeedData;
}
不能隐式地将类型'System.Collections.Generic.IEnumerable
'转换为'System.Collections.ObjectModel.ObservableCollection '。存在显式转换(您是否缺少强制类型转换?)
从你的错误消息中,你可以看到你将得到System.Collections.Generic.IEnumerable类型的数据outfitFeedData由LINQ result.
internal ObservableCollection<ProductModel> GetProducts()
{
var outfitFeedData = firebase
.Child("Products")
.AsObservable<ProductModel>()
.AsObservableCollection().Select(item => new ProductModel
{
Type = "K",
});
return outfitFeedData;
}
但是你通过GetProducts方法将List数据类型转换为ObservableCollection,我认为这是问题所在。
请按照以下代码修改ObservableCollection ProductList:
private List<ProductModel> _ProductList;
public List<ProductModel> ProductList
{
get { return _ProductList; }
set
{
_ProductList = value;
OnPropertyChanged();
}
}
然后修改GetProducts()方法的返回值。
internal List<ProductModel> GetAllPersons()
{
var outfitFeedData= (firebase
.Child("Products")
.OnceAsync<ProductModel>()).Select(item => new ProductModel
{
Type = "K",
}).ToList();
return outfitFeedData;
}
注意:我建议你可以实现Async和Await从firebase获取数据,如下所示:
public async Task<List<Person>> GetAllPersons()
{
return (await firebase
.Child("Persons")
.OnceAsync<Person>()).Select(item => new Person
{
Name = item.Object.Name,
PersonId = item.Object.PersonId
}).ToList();
}