You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中JSON加载到CollectionView失败及子项访问问题排查

.NET Maui CollectionView 加载JSON数据问题修复方案

1. 修正数据模型的序列化匹配问题

你的JSON属性为Name(首字母大写),但模型中定义的是name(小写),序列化时无法自动映射;同时类名存在拼写错误ProdcutsItem→ProductsItem,修正后代码:

public class ProductModel
{
    public class ProductList
    {
        public ObservableCollection<ProductsItem> Products { get; set; }
    }

    public class ProductsItem
    {
        // 与JSON属性名保持一致,确保序列化映射成功
        public string Name { get; set; }
        public int Price { get; set; }
    }
}

若不想修改属性名,也可通过特性指定映射关系:

[JsonProperty("Name")]
public string name { get; set; }

2. 简化ViewModel的集合结构

你反序列化得到的是单个ProductList对象,无需用ObservableCollection<ProductList>包裹,直接使用单个对象即可,简化后ViewModel代码:

public partial class ProductVM : ObservableObject
{
    [ObservableProperty]
    ProductModel.ProductList productList;

    [RelayCommand]
    async void LoadProducts()
    {
        var jsonContent = File.ReadAllText("D:\\Products.json");
        ProductList = JsonConvert.DeserializeObject<ProductModel.ProductList>(jsonContent);
        
        if (ProductList?.Products != null)
        {
            await Shell.Current.DisplayAlert("", $"产品数量:{ProductList.Products.Count}", "Ok");
        }
    }
}

3. 修正XAML绑定错误

  • CollectionView的ItemsSource直接绑定到ProductList.Products
  • ItemTemplate的上下文是单个ProductsItem,直接绑定其属性即可,同时指定正确的x:DataType
<!-- 需在XAML根节点添加模型命名空间引用,示例:xmlns:model="clr-namespace:你的项目命名空间" -->
<CollectionView BackgroundColor="Bisque" ItemsSource="{Binding ProductList.Products}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="model:ProductModel.ProductsItem">
            <Grid Padding="10">
                <Label Text="{Binding Name}" FontSize="16"/>
                <Label Text="{Binding Price, StringFormat='价格:{0:C}'}" 
                       Grid.Row="1" FontSize="14" TextColor="Gray"/>
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

4. 必要的上下文设置

确保页面的BindingContext已设置为ProductVM实例,比如在页面后台代码中:

public YourPage()
{
    InitializeComponent();
    BindingContext = new ProductVM();
}

内容的提问来源于stack exchange,提问作者SecGen Unity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 19:35:19