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

.NET Maui打开含ListView页面触发System.Reflection.TargetInvocation异常

MAUI ListView加载User数据触发TargetInvocation异常的解决方法

编译器无报错,但打开包含ListView的ContactPage时触发System.Reflection.TargetInvocation异常,以下是原代码:

原C#代码

using System.Collections.ObjectModel;

namespace GoogleMessenger.Pages;

public partial class ContactPage : ContentPage
{
    public ObservableCollection<User> Contact { get; set; } = new ObservableCollection<User>();
    public List<User> UserList { get; set; }
    public ContactPage()
    {
        InitializeComponent();
        BindingContext = this;

    }

    protected override void OnAppearing()
    {
        UserList = new List<User>()
        {
            new User() {Username = "something", Email = "something@something.com", LastMessage = "something! Lorem Ipsum...", ImageSource = "dotnet_bot.jpg"},
            new User() {Username = "something", Email = "something@something.com", LastMessage = "Lorem 10min something...", ImageSource = "dotnet_bot.jpg.jpg"},

        };


        if (!UserList.Any())
        {
            foreach (var user in UserList)
            {
                var userCopy = user;
                Contact.Add(userCopy);
            }
        }
        base.OnAppearing();
    }
      
}

原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"
             xmlns:pages="clr-namespace:GoogleMessenger.Pages"
             x:Class="GoogleMessenger.Pages.ContactPage"
             Title="ContactPage"
             >
    <ContentPage.BindingContext>
        <pages:ContactPage></pages:ContactPage>
    </ContentPage.BindingContext>
 
    <ListView ItemsSource="{Binding Contact}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid Padding="10">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto" />
                        <RowDefinition Height="Auto" />
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Image Grid.RowSpan="2"
                           Source="{Binding ImageSource}"
                           Aspect="AspectFill"
                           HeightRequest="60"
                           WidthRequest="60" />
                    <Label Grid.Column="1"
                           Text="{Binding Username}"
                           FontAttributes="Bold" />
                    <Label Grid.Row="1"
                           Grid.Column="1"
                           Text="{Binding LastMessage}"
                           FontAttributes="Italic"
                           VerticalOptions="End" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</ContentPage>

核心错误原因

  • 循环实例化页面:XAML中通过<ContentPage.BindingContext>手动实例化ContactPage,页面初始化时会递归创建自身实例,引发无限循环,最终抛出TargetInvocation异常。
  • 集合填充逻辑错误:OnAppearing中判断!UserList.Any()才填充Contact集合,但刚初始化的UserList有2个元素,导致Contact始终为空,无法渲染数据。
  • 图片路径错误:第二个User的ImageSource为dotnet_bot.jpg.jpg,大概率不存在该图片文件,会引发图片加载异常。

修复步骤

  1. 移除XAML中的BindingContext声明
    删除XAML里的<ContentPage.BindingContext>节点,因为C#构造函数中已通过BindingContext = this;设置绑定上下文,重复设置会导致循环实例化。

  2. 修正集合填充逻辑
    移除错误的判断条件,确保UserList有数据时能将元素添加到Contact集合中,同时添加清空操作避免页面重复出现时数据累加。

  3. 修正图片路径
    将第二个User的ImageSource改为正确的文件名dotnet_bot.jpg,并确保项目中存在该图片且设置了MauiImage生成操作。

修正后的代码

C#代码

using System.Collections.ObjectModel;

namespace GoogleMessenger.Pages;

public partial class ContactPage : ContentPage
{
    public ObservableCollection<User> Contact { get; set; } = new ObservableCollection<User>();
    public List<User> UserList { get; set; }

    public ContactPage()
    {
        InitializeComponent();
        BindingContext = this;
    }

    protected override void OnAppearing()
    {
        UserList = new List<User>()
        {
            new User() {Username = "something", Email = "something@something.com", LastMessage = "something! Lorem Ipsum...", ImageSource = "dotnet_bot.jpg"},
            new User() {Username = "something", Email = "something@something.com", LastMessage = "Lorem 10min something...", ImageSource = "dotnet_bot.jpg"},
        };

        // 先清空集合避免重复添加,再填充数据
        Contact.Clear();
        foreach (var user in UserList)
        {
            Contact.Add(user);
        }

        base.OnAppearing();
    }
}

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"
             xmlns:pages="clr-namespace:GoogleMessenger.Pages"
             x:Class="GoogleMessenger.Pages.ContactPage"
             Title="ContactPage">

    <ListView ItemsSource="{Binding Contact}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <Grid Padding="10">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="Auto" />
                            <RowDefinition Height="Auto" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="Auto" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <Image Grid.RowSpan="2"
                               Source="{Binding ImageSource}"
                               Aspect="AspectFill"
                               HeightRequest="60"
                               WidthRequest="60" />
                        <Label Grid.Column="1"
                               Text="{Binding Username}"
                               FontAttributes="Bold" />
                        <Label Grid.Row="1"
                               Grid.Column="1"
                               Text="{Binding LastMessage}"
                               FontAttributes="Italic"
                               VerticalOptions="End" />
                    </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:00:46