如何清理ContentView中的MediaElement?

问题描述 投票:0回答:1

我正在使用 Maui Community 工具包中的 MediaElement 控件。我需要在多个页面上使用它,并在其上添加一些额外的 UI 元素,因此我为此创建了一个自定义控件 (ContentView),然后在不同的页面中使用该控件。

现在,当您尝试从官方示例中了解如何正确使用 MediaElement 控件时,您会发现每当使用该控件的页面离开时,您都必须清理 MediaElement:

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

这对我来说是一件棘手的事情:当我在 ContentView 中进行此调用时,应用程序崩溃了。我无法捕获异常,但显然这不是正确的方法,而且我误解了 ContentView 对象生命周期的一些内容。

如果有人能让我知道如何在 ContentView 中正确、安全地使用 MediaElement,我将非常感激,感谢您的任何意见!

c# maui mediaelement maui-community-toolkit
1个回答
0
投票

我还是建议你在Page的UnLoaded事件中释放MediaElement。

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>

CustomContentView.cs:

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

并在页面中使用自定义内容视图:

<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"/>

以及页面的卸载事件:

private void ContentPage_Unloaded(object sender, EventArgs e)
{
    contentview.ReleaseMediaElement();
}
© www.soinside.com 2019 - 2024. All rights reserved.