.NET Maui 自定义处理程序不工作,官方文档有误?

.NET Maui Custom Handlers not working, official docs is wrong?

我正在使用 .NET MAUI 制作一个应用程序,我正在尝试为特定的控件实例实现自定义处理程序(例如,一些条目应该使用我创建的自定义处理程序)。为此,我遵循了官方 MS docs。以下是他们告诉我使用的设置:

1.First 创建 Entry 控件的子类:

using Microsoft.Maui.Controls;

namespace MyMauiApp
{
    public class MyEntry : Entry
    {
    }
}

2.I 然后自定义 EntryHandler 以对 MyEntry 实例执行所需的修改:

using Microsoft.Maui;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Graphics;

namespace MauiApp1
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            Microsoft.Maui.Handlers.EntryHandler.EntryMapper[nameof(IView.Background)] = (handler, view) =>
            {
                if (view is MyEntry)
                {
#if __ANDROID__
                    handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
                  handler.NativeView.BackgroundColor = Colors.Red.ToNative();
                  handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
                  handler.NativeView.Background = Colors.Red.ToNative();
#endif
                }
            };
        }
    }
}

问题:这给了我以下错误:

Severity Code Description Project File Line Suppression State Error CS0021 Cannot apply indexing with [] to an expression of type 'IPropertyMapper<IEntry, EntryHandler>' MyMauiApp (net6.0-android), MyMauiApp (net6.0-ios), MyMauiApp (net6.0-windows10.0.19041) C:\Users\xxxxxx\source\repos\MyMauiApp\MyMauiApp\App.xaml.cs 24 Active

正如我所说,我完全按照文档进行操作,但仍然出现此错误。我读到其他人也有这个问题。有人可以帮忙吗?

似乎通过此 pr here and here.

在这方面进行了一些重大更改

看起来这已经完成,因此您可以使用 AppendToMappingPrependToMapping 在映射器中级联自定义,或者使用 ModifyMapping.[=19 一起修改整个映射=]

这里不解释所有变化,让我们关注您的情况。这意味着而不是这一行 Microsoft.Maui.Handlers.EntryHandler.EntryMapper[nameof(IView.Background)] = (handler, view) =>

您现在应该声明为:Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>

请注意,您现在也应该在右括号中添加一个 ),使完整代码成为:

Microsoft.Maui.Handlers.EntryHandler.EntryMapper.AppendToMapping(nameof(IView.Background), (handler, view) =>
{
    if (view is MyEntry)
    {
#if __ANDROID__
        handler.NativeView.SetBackgroundColor(Colors.Red.ToNative());
#elif __IOS__
        handler.NativeView.BackgroundColor = Colors.Red.ToNative();
        handler.NativeView.BorderStyle = UIKit.UITextBorderStyle.Line;
#elif WINDOWS
        handler.NativeView.Background = Colors.Red.ToNative();
#endif
    }
});

我会看看是否可以在这里和那里更新文档,希望这不会再次中断 ;)

编辑:为此

更新了wiki page