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

.NET MAUI中ViewModel的ObservableCollection绑定与空引用异常问题

.NET MAUI 新增页面异常问题解决方案

环境信息

  • .NET 7
  • CommunityToolKit.Mvvm 8.1.0

问题场景

现有多个运行正常的.NET MAUI页面,新增页面时出现三类异常,ViewModel结构与正常页面一致,相关代码如下:

数据对象定义

public class allRegsGroupped
{
    public Guid? visualId { get; set; }
    public Guid? eventId { get; set; }
    public string? groupName { get; set; }
}

ViewModel 代码

using CommunityToolkit.Mvvm.ComponentModel;
using Newtonsoft.Json;
using SharedModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.ViewModels
{
public partial class ManageEventViewModel : ObservableObject, IQueryAttributable
{
    [ObservableProperty]
    ObservableCollection<allRegsGroupped> allGroupRegs;

    [ObservableProperty]
    allRegsGroupped test;

    EventPublicID _selectedEvent;

    public ManageEventViewModel() { }

    public void ApplyQueryAttributes(IDictionary<string, object> query)
    {
        _selectedEvent = query["selectedEvent"] as EventPublicID;
    }

    public async Task LoadAsync()
    {
        App.Globals.SetHttpClient();

        try
        {
            EventPublicID epi = _selectedEvent;

            var json = JsonConvert.SerializeObject(epi, Formatting.Indented);
            var content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");

            var response = await App.Globals.MyHttpClient.PostAsync(App.Globals.APIURL + "getAllRegistrationsForEvent", content);
            var allGroupsResponse = await response.Content.ReadAsStringAsync();

            if (!string.IsNullOrEmpty(allGroupsResponse))
            {
                List<allRegsGroupped> listOfGroups = JsonConvert.DeserializeObject<List<allRegsGroupped>>(allGroupsResponse);

                if (listOfGroups != null)
                {
                    AllGroupRegs = new ObservableCollection<allRegsGroupped>(
                        listOfGroups.OrderBy(x => x.groupName ?? string.Empty)
                    );
                }
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
        }
    }
    // 省略其他代码
}

XAML 代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="App.Pages.ManageEventPage"
         Title="Manage Event"
         xmlns:viewmodel="clr-namespace:App.ViewModels"
         xmlns:dm="clr-namespace:SharedModels;assembly=SharedModels"
         x:DataType="viewmodel:ManageEventViewModel"
         NavigatedTo="ContentPage_NavigatedTo"
         >
         
<VerticalStackLayout>
<CollectionView ItemsSource="{Binding AllGroupRegs}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="dm:allRegsGroupped">
            <VerticalStackLayout>
                <Label Text="{Binding groupName}" FontAttributes="Bold" />
            </VerticalStackLayout>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>
</VerticalStackLayout>
</ContentPage>

问题解决

1. XFC0045 绑定错误:找不到groupName属性

原因:页面设置了x:DataType="viewmodel:ManageEventViewModel",DataTemplate未单独指定数据类型时,绑定系统默认使用页面的ViewModel类型,而groupName属于allRegsGroupped对象,并非ViewModel的属性。

解决方案:给DataTemplate添加x:DataType="dm:allRegsGroupped"(dm是XAML中导入的SharedModels命名空间别名),明确绑定的数据对象类型。

2. AllGroupRegs赋值时的空引用异常

可能原因:

  • listOfGroups.OrderBy(x => x.groupName)中存在groupName为null的项,OrderBy处理null时引发异常;
  • 原代码使用response.Content.ReadAsStringAsync().Result导致异步死锁,间接引发空引用;
  • VS编译缓存导致的虚假异常。

解决方案:

  • 处理groupName为null的情况,排序时用x.groupName ?? string.Empty替代直接引用;
  • 将ReadAsStringAsync().Result改为await ReadAsStringAsync(),避免异步死锁;
  • 若仍出现异常,清理项目的bin和obj文件夹后重新编译。

3. ViewModel突然出现大量可观察属性解析错误

原因:VS2022的IntelliSense缓存或CommunityToolkit.Mvvm的源代码生成器缓存异常。

解决方案:

  • 关闭VS2022,删除项目根目录下的.vs文件夹、bin和obj文件夹,重新打开项目;
  • 更新VS2022到最新稳定版本,或升级CommunityToolkit.Mvvm到最新版本;
  • 尝试在项目属性中禁用然后重新启用“启用源代码生成器”选项。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:21:04