在 .NET MAUI 中重复使用效果

虽然使用 .NET Multi-platform App 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 针对其 RoutingEffect 实现注册 PlatformEffect 实现。

使用效果

通过将效果添加到控件的 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>