English 中文(简体)
为什么我的收 Collection 网上MAUI中添加重复项目的观点?
原标题:Why is my CollectionView adding duplicate items in .NET MAUI?

我的集思文为何一再增加同样的内容?

Here s what happens exactly:
On every load (on scroll) I want to load 5 more items into my CollectionView, but this is what happens:

  • The items 1,2,3,4,5 are added, then on scroll 1,2,3,4,5 are added again, and 1,2,3,4,5 again on scroll, etc.
  • Using Task.Delay(1000) the items 1,2,3,4,5 are added, then 1,2,3,4,5 again before adding 6,7,8,9,10 etc.
  • Using DisplayAlert() items are added without repitition for some reason. Obviously it s not a solution.

它像显示警示原因的拖延一样,为处理下一个项目留出了时间。 显然,我不想显示警惕,但收集工作在我使用时按预期进行。

This is my CollectionView with "posts":

<CollectionView ItemsSource="{Binding Posts}"
                ItemTemplate="{StaticResource CommunityItemTemplateSelector}"
                RemainingItemsThresholdReachedCommand="{Binding PopulateCommand}"
                RemainingItemsThreshold="0">
    <!-- Using DataTemplates to populate -->
</CollectionView>

This is the ViewModel populating it:
Populates the collection of items with new "posts" when the page appears or you hit the bottom of the CollectionView.

private CommunityService communityService { get; set; }

private int start = 0;
private int limit = 5;
private List<CommunityItem> posts { get; set; } = new();
public ObservableRangeCollection<CommunityItem> Posts { get; private set; } = new();

public Command OnAppearingCommand { get; private set; }
public Command PopulateCommand { get; private set; }

public CommunityViewModel(CommunityService communityService)
{
    this.communityService = communityService;

    OnAppearingCommand = new Command(Appearing);
    PopulateCommand = new Command(Populate);
}

private void Appearing()
{
    Posts.Clear();
    Populate();
}

private async void Populate()
{
    posts.Clear();

    await Task.Delay(250);

    posts = await communityService.GetPosts(start, limit);

    start += limit;

    if (posts.Count > 0)
        Posts.AddRange(posts);
}

This is the API getting new "posts":
It s not the API, this has been tested with Postman and works fine!

public class CommunityService : BaseService
{
    public List<CommunityItem> List = new();

    public async Task<List<CommunityItem>> GetPosts(int start, int limit)
    {
        string range = "&start=" + start + "&limit=" + limit;

        try
        {
            var response = await http.GetAsync(this.uri + "/post" + range + this.key);

            if (response.IsSuccessStatusCode && response.Content is not null)
                List = await response.Content.ReadFromJsonAsync<List<CommunityItem>>();

            // Somewhat solving the problem:
            await Task.Delay(1000);

            // Solving it completely for some reason, but shows an alert:
            await Application.Current.MainPage.DisplayAlert("Debug", "Waiting", "OK");
        }
        catch (Exception e)
        {
            // Debug
        }

        return List;
    }
}
问题回答

Well, according to Panagiotis Kanavos s comment, as a wiki answer:

这是因为async void,而该编码本身就是一种ug。 不能等待<条码>sync void。 因此,可以立即进行指挥“组合”,而该构成部分在<社区服务.GetPosts之前不断要求新的数据,从而有机会完成和更新计算。 Either make their code synchronous or use the AsyncRelayCommand from the MAUI Community Toolkit.

Switching to AsyncRelayCommand can solve the problem to a certain extent.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签