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

Xamarin.Forms使用CollectionView无法显示员工姓名、任务及日期求助

问题修复方案

你代码存在3处核心错误,修改后即可正常展示:

1. 修正XAML分组模板配置

你误用了HeaderTemplate(全局顶部头部),分组的每组头部需要用GroupHeaderTemplate,同时CollectionView的模板不需要ViewCell(为ListView专属组件),修改后XAML如下:

<CollectionView x:Name="CV" IsGrouped="True">
    <!-- 分组头部模板:每个员工对应一组的头部 -->
    <CollectionView.GroupHeaderTemplate>
        <DataTemplate>
            <StackLayout Padding="10,5">
                <Label Text="{Binding Name}" FontSize="Large"/>
                <Label Text="{Binding LastName}" FontSize="Large"/>
            </StackLayout>
        </DataTemplate>
    </CollectionView.GroupHeaderTemplate>
    <!-- 分组子项模板:每个任务的布局 -->
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <StackLayout Padding="20,5">
                <Label Text="{Binding Description}" FontSize="Medium"/>
                <Label Text="{Binding Deadline, StringFormat='截止日期:{0:yyyy-MM-dd}'}" FontSize="Medium"/>
            </StackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

2. 构造符合分组要求的数据源

开启IsGrouped="True"后,CollectionView要求数据源为分组集合:每个分组包含组头属性+子任务集合,你直接绑定子任务列表没有分组结构,自然无法正常展示。
首先创建分组包装类:

// 分组类:继承List<Duty>作为子项集合,同时包含员工信息作为组头绑定源
public class EmployeeDutyGroup : List<Duty>
{
    public string Name { get; set; }
    public string LastName { get; set; }

    public EmployeeDutyGroup(Employee employee) : base(employee.Duties)
    {
        Name = employee.Name;
        LastName = employee.LastName;
    }
}

3. 修正业务逻辑代码

补全Duty的外键赋值,然后构造分组集合绑定到CollectionView:

var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Mydb.db");
var db = new SQLiteConnection(dbpath);
db.CreateTable<Employee>();
db.CreateTable<Duty>();

var employee = new Employee
{
    Name = "Andrew",
    LastName = "Programmer"
};
db.Insert(employee);

var duty1 = new Duty()
{
    Description = "Project A Management",
    Deadline = new DateTime(2017, 10, 31),
    // 补全外键赋值,避免关联异常
    EmployeeId = employee.Id
};

var duty2 = new Duty()
{
    Description = "Reporting work time",
    Deadline = new DateTime(2022, 12, 31),
    // 补全外键赋值
    EmployeeId = employee.Id
};

db.Insert(duty1);
db.Insert(duty2);

employee.Duties = new List<Duty> { duty1, duty2 };
db.UpdateWithChildren(employee);

var employeeStored = db.GetWithChildren<Employee>(employee.Id);

// 构造分组集合绑定
var groupList = new List<EmployeeDutyGroup>
{
    new EmployeeDutyGroup(employeeStored)
};
// 如果要展示所有员工的任务,循环查询所有Employee并加入groupList即可
CV.ItemsSource = groupList;

如果需要展示多个员工的分组任务,只需要把所有查询到的Employee对象都包装成EmployeeDutyGroup加入groupList即可。

内容的提问来源于stack exchange,提问作者Fawaz Ahmed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 00:15:07