Share via


在 .NET MAUI 中重複使用效果

雖然使用 .NET 多平臺應用程式 UI (.NET MAUI) 處理程式來自定義控件有許多優點,但仍然可以在 .NET MAUI 應用程式中使用 Xamarin.Forms 效果。 如需效果的詳細資訊,請參閱 Xamarin.Forms 效果

將 Xamarin.Forms 效果移轉至 .NET MAUI 的程式是:

  1. 從效果類別中移除效果屬性。 如需詳細資訊,請參閱 移除效果屬性
  2. 拿掉效果 using 指示詞。 如需詳細資訊,請參閱 移除using指示詞
  3. 將效果程式代碼新增至 .NET MAUI 應用程式專案中的適當位置。 如需詳細資訊,請參閱 新增效果程序代碼
  4. 註冊效果。 如需詳細資訊,請參閱 註冊效果
  5. 使用您的 .NET MAUI 效果。 如需詳細資訊,請參閱 取用效果

拿掉效果屬性

任何 ResolutionGroupNameAttributeExportEffectAttribute 屬性都應該從您的效果類別中移除。

拿掉using指示詞

和命名空間的任何參考Xamarin.FormsXamarin.Forms.Platform.*都應該從您的效果類別中移除。

新增效果程序代碼

如果您使用 .NET MAUI 多目標專案,您的效果程式代碼應該合併成單一檔案,並放在 [平臺] 資料夾外。 這需要您將實 RoutingEffect 作和 PlatformEffect 實作結合成單一檔案,並使用平臺程式代碼周圍的條件式編譯。 不過,如果您的方案每個平臺都有個別的專案,則您應該將平臺特定效果檔案移至對應的專案。

在 .NET MAUI 中,類別 RoutingEffect 位於 命名空間中 Microsoft.Maui.Controls 。 這個命名空間是 .NET MAUI 的隱含 global using 指示詞之一,因此您不需要為其新增 using 指示詞。 不過,類別 PlatformEffect 位於 命名空間中 Microsoft.Maui.Controls.Platform ,您必須新增 using 指示詞。

下列程式代碼範例顯示類別 FocusRoutingEffect 及其平台實作結合成單一檔案:

using Microsoft.Maui.Controls.Platform;

namespace MyMauiApp.Effects;

internal class FocusRoutingEffect : RoutingEffect
{
}

#if ANDROID
internal class FocusPlatformEffect : PlatformEffect
{
    protected override void OnAttached()
    {
        // Customize the control here
    }

    protected override void OnDetached()
    {
        // Cleanup the control customization here
    }
}
#elif IOS
internal class FocusPlatformEffect : PlatformEffect
{
    protected override void OnAttached()
    {
        // Customize the control here
    }

    protected override void OnDetached()
    {
        // Cleanup the control customization here
    }
}
#elif WINDOWS
internal class FocusPlatformEffect : PlatformEffect
{
    protected override void OnAttached()
    {
        // Customize the control here
    }

    protected override void OnDetached()
    {
        // Cleanup the control customization here
    }
}
#endif

註冊效果

在您的 .NET MAUI 應用程式專案中,開啟 MauiProgram.cs,並在 方法中的 CreateMauiApp 物件上MauiAppBuilder呼叫 ConfigureEffects 方法:

public static MauiApp CreateMauiApp()
{
  var builder = MauiApp.CreateBuilder();
  builder
    .UseMauiApp<App>()
    .ConfigureEffects(effects =>
    {
      effects.Add<FocusRoutingEffect, FocusPlatformEffect>();
    });

  return builder.Build();
}

效果會向 ConfigureEffects 方法註冊,該方法 configureDelegate 會針對其實作註冊 PlatformEffectRoutingEffect 作。

取用效果

將效果新增至 Effects 控件的集合,即可在 .NET MAUI 應用程式中取用效果:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MyMauiApp.Effects"
             x:Class="MyMauiApp.MainPage">
    <VerticalStackLayout>
        <Entry Text="Enter your text">
            <Entry.Effects>
                <local:FocusRoutingEffect />
            </Entry.Effects>
        </Entry>
    </VerticalStackLayout>
</ContentPage>