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

Xamarin.Forms中如何为ListView绑定自定义类列表并显示其属性?

解决ListView绑定ObservableCollection自定义类属性的问题

问题根源

  1. x:DataType 上下文错误:给整个ListView设置x:DataType="vm:CustomtViewModel"后,ItemTemplate的默认绑定上下文变成了ViewModel,但ViewModel里并没有Id属性,因此报错。每个列表项的绑定上下文应该是集合中的myCustomClass实例,需要单独给DataTemplate指定x:DataType。
  2. 错误使用StaticSource:StaticSource是引用资源字典里的单个静态实例,而列表项需要绑定当前集合的条目对象,完全不需要用这个。
  3. 语法拼写错误:XAML控件需大写开头,应为<Label>而非<label>;绑定语法里的逗号位置错误且多余。

修正后的代码

1. 确认命名空间引入正确

在ContentPage根标签里补充正确的命名空间引用:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:vm="clr-namespace:myApp.ViewModels"
             xmlns:local="clr-namespace:myApp.Models"
             x:Class="myApp.Pages.YourPage">

2. 修正ListView绑定代码

<ListView
    x:DataType="vm:CustomViewModel" <!-- 修正笔误:CustomtViewModel → CustomViewModel -->
    BackgroundColor="LightSlateGray"
    HasUnevenRows="True"
    HorizontalOptions="FillAndExpand"
    ItemsSource="{Binding myCustomObservableCollection}"
    SeparatorColor="Black">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:myCustomClass"> <!-- 指定每个列表项的类型为自定义类 -->
            <ViewCell> <!-- ListView的ItemTemplate必须用ViewCell包裹 -->
                <Label Text="{Binding Id}" /> <!-- 直接绑定当前条目对象的Id属性 -->
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

3. 移除无效资源定义

你在ContentPage.Resources里定义的<local:myCustomClass x:Key="myCustomClass" />完全没用,直接删除即可——列表项的数据源来自集合中的动态对象,不需要静态实例。

额外检查点

  • 确保ViewModel中的myCustomObservableCollection是公共属性,且ViewModel已设置为当前ContentPage的BindingContext。
  • 确认myCustomClass的Id属性为公共访问权限,你的代码中这部分实现是正确的。

内容的提问来源于stack exchange,提问作者Michele Rava

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:55:13