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.