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

MAUI跳转页面后CollectionView无内容显示问题求助

问题描述

DataPage中的CollectionView与主页面实现几乎完全一致,但跳转至该页面后,仅能看到CollectionView的黄色背景,却不显示任何内部内容。已确认ItemsSource、DataTemplate及图片源的绑定均正确,唯一差异为页面跳转方式。

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"
             Title="DataPage"
            xmlns:model="clr-namespace:MyApp.Views"
            xmlns:vm="clr-namespace:MyApp.Views"
            x:Class="MyApp.Views.DataPage">
   
    <Grid BackgroundColor="Blue" ColumnDefinitions="*,*,*" 
          ColumnSpacing="5"
          RowDefinitions="*,*,*,*">
        <Image BackgroundColor="White" Grid.Row="0" Grid.Column="1" x:DataType="model:DataPage" Source="{Binding JimgSource}"
                                   HeightRequest="150"
                                   WidthRequest="300"
                               Margin="10"/>
        <CollectionView x:DataType="model:DataPage" Grid.Row="1" Grid.ColumnSpan="3" Grid.RowSpan="2" BackgroundColor="Yellow" Margin="10" ItemsSource="{Binding CurrentData}">
            <CollectionView.ItemTemplate>
                <DataTemplate  x:DataType="model:Data" >
                    <VerticalStackLayout BackgroundColor="Pink">
                    <Frame BackgroundColor="Aqua">

                        <Image Source="{Binding ImagesSource}" WidthRequest="100" HeightRequest="100"/> 
                    </Frame>
                    </VerticalStackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

        <Editor  HeightRequest="200" WidthRequest="350"  Grid.ColumnSpan="3"  Grid.Row="3" BackgroundColor="Beige"/>
        <Button x:DataType="model:DataPage" Command="{Binding PickfileData}"  Text="add"
                    WidthRequest="150"
                Grid.Row="4"
                    Grid.Column="1"
                VerticalOptions="End"/>
    </Grid>

</ContentPage>

后台代码

using System.Windows.Input;

namespace MyApp.Views;

public partial class DataPage : ContentPage
{

    public static ObservableCollection<Data> data { get; set; } = new();
    public static ObservableCollection<Data> CurrentData { get; set; } = new();
    public string JimgSource { get; set; }
    public int id { get; set; }
    public ICommand PickfileData { get; set; }

    public DataPage(TxtImgModel model)
    {
        InitializeComponent();
        PickfileData = new Command(DataButton);
        JimgSource = model.ImgSource;
        id = model.Id;
        CurrentData.Clear();
        foreach (var item in Data)
        {
            if (item.Id == model.Id) 
            {
                CurrentData.Add(item);
            }
        }

        BindingContext = this;
    }

    public async void DataButton()
    {
        var image = await MainPage.PickAndShow(PickOptions.Default);
        string Source = image.FullPath;
        Data dt = new Data { Id = this.id, ImagesSource = Source };
        data.Add(dt);
        CurrentData.Add(dt);
        var serializedData = JsonSerializer.Serialize(data);
        File.WriteAllText(MainPage.JsonDataPath, serializedData);

    }
}
public class Data
{
    public int Id { get; set; }

    public string ImagesSource { get; set;}
}

主页面跳转代码

public async void TappedImage(object sender, EventArgs e)
{
    Label Id = (Label)((Frame)sender).FindByName("Id");
    foreach (var item in TxtImage)
    {
        if (item.Id.ToString() == Id.Text)
        {
            DataPage Transient = new DataPage(item);
            await Navigation.PushAsync(Transient);
            break;
        }
    }
}
问题分析与解决方案

1. 静态集合冲突

CurrentData被定义为静态属性,所有DataPage实例共享同一个集合,新页面跳转时会继承之前的集合状态,导致数据显示异常。
修复:移除static修饰符,让每个页面实例拥有独立集合:

public ObservableCollection<Data> CurrentData { get; set; } = new();

2. 遍历集合的语法错误

构造函数中foreach (var item in Data)是错误的,Data是类名,应遍历静态的data集合:
修复:

foreach (var item in data)
{
    if (item.Id == model.Id) 
    {
        CurrentData.Add(item);
    }
}

3. 缺失属性变更通知

DataPage和Data类的属性未实现INotifyPropertyChanged接口,UI无法感知数据变化。
修复:给DataPage添加接口实现:

public partial class DataPage : ContentPage, INotifyPropertyChanged
{
    private ObservableCollection<Data> _currentData = new();
    private string _jimgSource;

    public ObservableCollection<Data> CurrentData
    {
        get => _currentData;
        set
        {
            _currentData = value;
            OnPropertyChanged();
        }
    }

    public string JimgSource
    {
        get => _jimgSource;
        set
        {
            _jimgSource = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // 其余代码保持不变
}

给Data类添加接口实现:

public class Data : INotifyPropertyChanged
{
    private int _id;
    private string _imagesSource;

    public int Id
    {
        get => _id;
        set
        {
            _id = value;
            OnPropertyChanged();
        }
    }

    public string ImagesSource
    {
        get => _imagesSource;
        set
        {
            _imagesSource = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

4. Grid布局越界

Grid仅定义了4行(索引0-3),但Button使用Grid.Row="4"会超出布局范围,可能影响页面渲染。
修复:修改Grid的RowDefinitions为*,*,*,*,*,或调整Button的Grid.Row为3以内的值。

5. 绑定上下文时机优化

建议在所有属性初始化完成后再设置BindingContext,避免UI绑定未初始化的属性:

public DataPage(TxtImgModel model)
{
    InitializeComponent();
    PickfileData = new Command(DataButton);
    JimgSource = model.ImgSource;
    id = model.Id;
    CurrentData.Clear();
    foreach (var item in data)
    {
        if (item.Id == model.Id) 
        {
            CurrentData.Add(item);
        }
    }

    // 最后设置绑定上下文
    BindingContext = this;
}

完成上述修改后,CollectionView即可正常显示内容。


内容的提问来源于stack exchange,提问作者Sh.sh94

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 13:18:09