分享方式:


共用

Browse sample. 流覽範例

本文說明如何使用 .NET 多平臺應用程式 UI (.NET MAUI) IShare 介面。 此介面提供 API,可將文字或 Web 連結等數據傳送至裝置共用函式。

介面的預設實作 IShare 可透過 Share.Default 屬性取得。 IShare介面和Share類別都包含在 命名空間中Microsoft.Maui.ApplicationModel.DataTransfer

提出共用要求時,裝置會顯示共享視窗,提示使用者選擇要共用的應用程式:

Share from your app to a different app

開始使用

若要存取 共用 功能,需要下列平臺特定設定:

不需要任何設定。

共用功能的運作方式是使用數據承載呼叫 RequestAsync 方法,其中包含要與其他應用程式共用的資訊。 ShareTextRequest.TextShareTextRequest.Uri 可以混合,而且每個平臺都會根據內容處理篩選。

public async Task ShareText(string text)
{
    await Share.Default.RequestAsync(new ShareTextRequest
    {
        Text = text,
        Title = "Share Text"
    });
}

public async Task ShareUri(string uri, IShare share)
{
    await share.RequestAsync(new ShareTextRequest
    {
        Uri = uri,
        Title = "Share Web Link"
    });
}

共用檔案

您也可以將檔案共享至裝置上的其他應用程式。 .NET MAUI 會自動偵測文件類型 (MIME) 並要求共用。 不過,操作系統可能會限制可以共用的文件類型。 若要共用單一檔案,請使用 ShareFileRequest 類型。

下列程式代碼範例會將文字檔寫入裝置,然後要求共用它:

public async Task ShareFile()
{
    string fn = "Attachment.txt";
    string file = Path.Combine(FileSystem.CacheDirectory, fn);

    File.WriteAllText(file, "Hello World");

    await Share.Default.RequestAsync(new ShareFileRequest
    {
        Title = "Share text file",
        File = new ShareFile(file)
    });
}

共用多個檔案

共用多個檔案與共用單一檔案稍有不同。 若要共用單一檔案,請使用 ShareMultipleFilesRequest 類型。

下列程式代碼範例會將兩個文字檔寫入裝置,然後要求共用它們:

public async Task ShareMultipleFiles()
{
    string file1 = Path.Combine(FileSystem.CacheDirectory, "Attachment1.txt");
    string file2 = Path.Combine(FileSystem.CacheDirectory, "Attachment2.txt");

    File.WriteAllText(file1, "Content 1");
    File.WriteAllText(file2, "Content 2");

    await Share.Default.RequestAsync(new ShareMultipleFilesRequest
    {
        Title = "Share multiple files",
        Files = new List<ShareFile> { new ShareFile(file1), new ShareFile(file2) }
    });
}

簡報位置

重要

本節僅適用於 iPadOS。

在 iPadOS 上要求共用或開啟啟動器時,您可以在快顯中呈現它。 這會指定彈出視窗會出現的位置,並直接指向箭號。 這個位置通常是啟動動作的控制件。 您可以使用 PresentationSourceBounds 屬性來指定位置:

await Share.RequestAsync(new ShareFileRequest
    {
        Title = Title,
        File = new ShareFile(file),
        PresentationSourceBounds = DeviceInfo.Platform == DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet
                                ? new Rect(0, 20, 0, 0)
                                : Rect.Zero
    });
await Launcher.OpenAsync(new OpenFileRequest
    {
        File = new ReadOnlyFile(file),
        PresentationSourceBounds = DeviceInfo.Platform == DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet
                                ? new Rect(0, 20, 0, 0)
                                : Rect.Zero
    });

這個處所述的一切同樣適用於 ShareLauncher

以下是可協助計算檢視界限的擴充方法:

public static class ViewHelpers
{
    public static Rect GetAbsoluteBounds(this Microsoft.Maui.Controls.View element)
    {
        Element looper = element;

        var absoluteX = element.X + element.Margin.Top;
        var absoluteY = element.Y + element.Margin.Left;

        // Add logic to handle titles, headers, or other non-view bars

        while (looper.Parent != null)
        {
            looper = looper.Parent;
            if (looper is Microsoft.Maui.Controls.View v)
            {
                absoluteX += v.X + v.Margin.Top;
                absoluteY += v.Y + v.Margin.Left;
            }
        }

        return new Rect(absoluteX, absoluteY, element.Width, element.Height);
    }
}

呼叫 時可以使用這個方法 RequestAsync

public Command<Microsoft.Maui.Controls.View> ShareCommand { get; } = new Command<Microsoft.Maui.Controls.View>(Share);

async void Share(Microsoft.Maui.Controls.View element)
{
    try
    {
        await Share.Default.RequestAsync(new ShareTextRequest
        {
            PresentationSourceBounds = element.GetAbsoluteBounds(),
            Title = "Title",
            Text = "Text"
        });
    }
    catch (Exception)
    {
        // Handle exception that share failed
    }
}

觸發 時 Command ,您可以傳入呼叫專案:

<Button Text="Share"
        Command="{Binding ShareWithFriendsCommand}"
        CommandParameter="{Binding Source={RelativeSource Self}}"/>

如需 類別的 ViewHelpers 範例,請參閱 裝載在 GitHub 上的 .NET MAUI 範例。

平台差異

本節說明共用 API 的平臺特定差異。