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

Xamarin.Forms嵌套ListView数据绑定报错XFC0045的问题求助

Xamarin.Forms嵌套ListView数据绑定报错XFC0045的问题求助

嗨,我来帮你解决这个绑定报错的问题!

这个XFC0045错误的核心原因是XAML强类型绑定的上下文继承问题:你给整个页面指定了x:DataType="viewmodels:ChecklistViewModel",这会让所有子元素默认继承这个绑定上下文——包括外层ListView的ItemTemplate里的DataTemplate。所以当你在模板里绑定ChecklistCategory时,系统会错误地去ChecklistViewModel里找这个属性,而不是当前的ChecklistSection对象,自然就找不到了。同理,内层ListView的模板也没有指定对应的模型类型,系统也不知道要绑定到ChecklistItem的属性上。

解决方案:给每个层级的DataTemplate指定明确的DataType

你只需要两步就能解决问题:

  1. 在XAML里引入你的模型所在的命名空间(请根据实际项目路径修改)
  2. 给每个DataTemplate添加x:DataType,明确当前绑定的上下文模型

修改后的完整XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewmodels="clr-namespace:xxx.xx.xxx.App.ViewModels"
             xmlns:models="clr-namespace:xxx.xx.xxx.App.Models" <!-- 新增模型命名空间 -->
             x:Class="xx.xx.xxx.App.Views.Checklist"
             x:DataType="viewmodels:ChecklistViewModel">
    <StackLayout>
        <ListView ItemsSource="{Binding ChecklistSections}">
            <ListView.ItemTemplate>
                <!-- 指定外层模板的上下文为ChecklistSection -->
                <DataTemplate x:DataType="models:ChecklistSection">
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding ChecklistCategory.Name}" />
                            <ListView ItemsSource="{Binding ChecklistItems}">
                                <ListView.ItemTemplate>
                                    <!-- 指定内层模板的上下文为ChecklistItem -->
                                    <DataTemplate x:DataType="models:ChecklistItem">
                                        <ViewCell>
                                            <StackLayout>
                                                <Label Text="{Binding ItemName}" />
                                            </StackLayout>
                                        </ViewCell>
                                    </DataTemplate>
                                </ListView.ItemTemplate>
                            </ListView>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</ContentPage>

额外小提示

嵌套ListView在Xamarin.Forms里偶尔会出现滚动交互冲突的问题,如果后续遇到滚动不顺畅的情况,可以考虑用CollectionView替代ListView,它对嵌套列表的支持会更友好哦。

备注:内容来源于stack exchange,提问作者sina .s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.22 07:47:58