Xamarin.Forms中如何为ListView绑定自定义类列表并显示其属性?
解决ListView绑定ObservableCollection自定义类属性的问题
问题根源
- x:DataType 上下文错误:给整个ListView设置
x:DataType="vm:CustomtViewModel"后,ItemTemplate的默认绑定上下文变成了ViewModel,但ViewModel里并没有Id属性,因此报错。每个列表项的绑定上下文应该是集合中的myCustomClass实例,需要单独给DataTemplate指定x:DataType。 - 错误使用StaticSource:
StaticSource是引用资源字典里的单个静态实例,而列表项需要绑定当前集合的条目对象,完全不需要用这个。 - 语法拼写错误: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
相关产品推荐
相关产品推荐

