MAUI中CollectionView无法显示集合数据的问题求助
自定义控件中CollectionView无法显示数据的解决方法
你遇到的问题核心是数据绑定上下文未正确配置以及集合类型适配问题,以下是具体修复方案和修改后的代码:
问题核心原因
- 绑定上下文缺失:XAML中的
{Binding Data2see}无法找到数据源,因为自定义控件默认BindingContext未指向自身 - 集合类型不适配:
Collection<T>未实现INotifyCollectionChanged接口,无法向UI层传递数据更新通知(即使初始化时添加数据,也建议用更适配MAUI的集合类型) - 布局冲突:根
StackLayout设为Horizontal会挤压垂直列表的CollectionView,导致显示异常
修改后的完整代码
XAML部分
<StackLayout xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="CustomControls.CustomControl.DataGrid2" xmlns:local="clr-namespace:CustomControls.CustomControl" HeightRequest="500" WidthRequest="500" Orientation="Vertical" <!-- 改为垂直布局,避免挤压列表 --> x:Name="Self" BindingContext="{x:Reference Self}"> <!-- 绑定上下文指向自身 --> <CollectionView x:Name="c2" ItemsLayout="VerticalList" x:DataType="local:DataGrid2" ItemsSource="{Binding Data2see}" > <CollectionView.Header> <StackLayout BackgroundColor="LightGray"> <Label Margin="10,0,0,0" Text="Monkeys" FontSize="Small" FontAttributes="Bold" /> </StackLayout> </CollectionView.Header> <CollectionView.Footer> <StackLayout BackgroundColor="LightGray"> <Label Margin="10,0,0,0" Text="Friends of Xamarin Monkey" FontSize="Small" FontAttributes="Bold" /> </StackLayout> </CollectionView.Footer> <CollectionView.ItemTemplate> <DataTemplate x:DataType="local:SomeDataExemple2"> <Grid Padding="10" ColumnDefinitions="100,100,100"> <Button Grid.Column="0" Text ="clickmenow2"/> <Entry Grid.Column= "1" Text="{Binding Name}"/> <Entry Grid.Column="2" Text="{Binding First_name}"/> </Grid> </DataTemplate> </CollectionView.ItemTemplate> </CollectionView> </StackLayout>
C#代码部分
namespace CustomControls.CustomControl { using System.Collections.ObjectModel; public partial class DataGrid2 : StackLayout { public DataGrid2() { // 改用ObservableCollection,支持数据变动通知UI更新 Data2see = new ObservableCollection<SomeDataExemple2>(); Data2see.Add(new SomeDataExemple2("hamid", "britel")); Data2see.Add(new SomeDataExemple2("mernissi", "wadie")); Data2see.Add(new SomeDataExemple2("mhamed", "chraibi")); Data2see.Add(new SomeDataExemple2("yazid", "alaoui")); Data2see.Add(new SomeDataExemple2("amine", "gogole")); Data2see.Add(new SomeDataExemple2("mehdi", "harras")); InitializeComponent(); // 也可以在这里设置 BindingContext = this; 替代XAML中的绑定配置 } public ObservableCollection<SomeDataExemple2> Data2see { get; set; } } public class SomeDataExemple2 { public SomeDataExemple2(string name1, string name2) { Name = name1; First_name = name2; } public string Name { get; set; } public string First_name { get; set; } } }
额外说明
- 如果无需动态修改集合数据,也可以保留
Collection<T>,但必须确保绑定上下文正确设置,不过ObservableCollection<T>是MAUI数据绑定的标准推荐类型 - 若根布局必须使用
Horizontal,需给CollectionView设置足够的WidthRequest,避免被其他控件挤压
内容的提问来源于stack exchange,提问作者W Mernissi
相关产品推荐
相关产品推荐

