How to cleanup MediaElement in ContentView?

98 Views Asked by At

I am using the MediaElement control from the Maui Community toolkit. I need to use it on several pages, and add some extra UI elements on it, so I created a custom control (ContentView) for that, and then use that control in my different pages.

Now when you try to understand how to properly use the MediaElement control from the official sample, you can see that whenever the page which uses the control is left, you have to clean up the MediaElement:

void BasePage_Unloaded(object? sender, EventArgs e)
{
    // Stop and cleanup MediaElement when we navigate away
    mediaElement.Handler?.DisconnectHandler();
}

Here is the tricky thing for me: when I make this call inside a ContentView, the application crashes. I am not able to catch an exception but obviously this is not the way to go and I am misunderstanding something about the lifecycle of ContentView objects.

I would very much appreciate if someone can let me know how you are supposed to properly and safely use MediaElement in a ContentView, thanks for any input!

1

There are 1 best solutions below

0
On BEST ANSWER

I still suggest you release the MediaElement in the Page's UnLoaded event.

The CustomContentView.xmal:

<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:mct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
             x:Class="MauiApp2.MyContentView">
    <VerticalStackLayout>
        <mct:MediaElement x:Name="media" Source="embed://ttt.mp4" HeightRequest="300"/>
        <Label
            Text="Welcome to .NET MAUI!"
            VerticalOptions="Center"
            HorizontalOptions="Center" />
    </VerticalStackLayout>
</ContentView>

The CustomContentView.cs:

public partial class MyContentView : ContentView
{
      public MyContentView()
      {
            InitializeComponent();
      }
      public void ReleaseMediaElement()
      {
            media.Handler?.DisconnectHandler();
      }
}

And use the custom contentview in the page:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiApp2"
             x:Class="MauiApp2.MainPage"
             Unloaded="ContentPage_Unloaded"
             >

    <ScrollView x:Name="MyScroll">
        <VerticalStackLayout
            x:Name="MyStack"
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Start"
            BackgroundColor="AliceBlue">
            <local:MyContentView x:Name="contentview"/>

And the page's unloaded event:

private void ContentPage_Unloaded(object sender, EventArgs e)
{
    contentview.ReleaseMediaElement();
}