最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to prevent item recycling in a CollectionView in .NET MAUI? - Stack Overflow

programmeradmin0浏览0评论

I'm working on a TikTok-like video scrolling experience using a CollectionView in .NET MAUI. Each item in the CollectionView contains a video element (specifically a MediaElement) that plays when visible. The page will only ever display four videos at a time, so memory usage is not a significant concern for me.

However, I've encountered a couple of issues due to the default recycling behavior of the CollectionView:

Problems:

State preservation issues: When a video item is recycled, its state is not preserved. To work around this, I've been manually saving the video state (like playback position) in a dictionary and restoring it using SeekTo method when the video reappears. This workaround, however, makes the scrolling experience feel less smooth and negatively impacts the UX.

Resource cleanup issues: The MediaElement documentation mentions that resources should be released using DisconnectHandler to avoid memory leaks. But when I attempt to call DisconnectHandler on recycled MediaElements, I get an ObjectDisposedException. I suspect this is because the CollectionView has already disposed of the MediaElement but didn't call DisconnectHandler beforehand, leading to resource leaks.

What I've Tried:

I attempted to replace the DataTemplate with a list of ContentView instances (each containing a MediaElement) in the ItemsSource, hoping this would prevent recycling. Unfortunately, this had no effect.

What I Need:

I'm looking for a way to:

Disable or prevent item recycling in the CollectionView entirely (even if it impacts performance slightly, as I only have four items). Ensure proper cleanup of MediaElement resources when the items are removed or disposed.

Is there a way to achieve this in .NET MAUI, or should I consider an alternative approach to implement this kind of scrolling video UI?

EDIT

I tried to use the SfListView since (compared to the MAUI CollectionView) it still has the CachingStrategy property. The problem is that even with this property set on CreateNewTemplate the MediaElements get reset.

发布评论

评论列表(0)

  1. 暂无评论