using|MAUI 移植 Xamarin.Forms 自定义渲染器( 二 )

  • < ContentPagexmlns= "http://xamarin.com/schemas/2014/forms"xmlns:x= "http://schemas.microsoft.com/winfx/2009/xaml"x:Class= "App2.Views.AboutPage"xmlns:my= "clr-namespace:App2"> < Grid> <!--此处略过许多代码-->< my:MyButtonText= "About!"/> </ Grid> </ ContentPage>
    第四步
    启动Android项目 , 预览效果 , 如下所示:
    using|MAUI 移植 Xamarin.Forms 自定义渲染器
    文章图片

    说明:通过上面几步, 我们轻松的完成了在Xamarin当中自定义渲染器并且显示在模拟器当中 , 接下来 , 主要的任务是将Xamarin现有的自定义渲染器移植到MAUI项目中 。
    渲染器移植至MAUI项目
    第一步
    这里 , 直接创建名为MAUIRender的新MAUI项目 。
    using|MAUI 移植 Xamarin.Forms 自定义渲染器
    文章图片

    第二步
    然后 , 我们把Xamarin中创建的MyButton与MyButtonRender直接复制到MAUI的项目中 , 如下所示:
    using|MAUI 移植 Xamarin.Forms 自定义渲染器
    文章图片

    MyButtonRender类修改如下:
    usingApp2;usingAndroid.Content; usingMicrosoft.Maui.Controls.Platform;usingMicrosoft.Maui.Controls;usingMicrosoft.Maui.Controls.Compatibility.Platform.Android.FastRenderers;namespaceMAUIRender{publicclass MyButtonRender : ButtonRenderer{publicMyButtonRender(Context context) : base(context){}
    protectedoverride void OnElementChanged(ElementChangedEventArgs<Button> e){base.OnElementChanged(e);if(Control!= null)Control.SetBackgroundColor(global: :Android.Graphics.Color.Red);}}}
    说明:此处更新涉及更新命名空间引用
    • 移除旧的Xamarin引用: using Xamarin.Forms.Platform.Android; using Xamarin.Forms;
    • 添加新的MAUI引用: using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Platform; using Microsoft.Maui.Controls.Compatibility.Platform.Android.AppCompat;
    移除 [assembly:ExportRenderer(typeof(MyButton),typeof(MyButtonRender))] (原因下面说)
    MyButton类修改如下:
    usingMicrosoft.Maui.Controls; namespaceApp2{publicclassMyButton: Button{
    }}
    说明:using Xamarin.Forms;更新为:using Microsoft.Maui.Controls;
    【using|MAUI 移植 Xamarin.Forms 自定义渲染器】第三步
    依赖注入自定义的Render
    上面所讲到移除 [assembly: ExportRenderer(typeof(MyButton) ,typeof(MyButtonRender))] 声明 , 在Xamarin当中 , 渲染器强制声明在Android项目中 , 耦合性很强 。 这一点在MAUI项目当中 , 则是通过Startup类中依赖注入的形式添加 , 通过扩展方法 ConfigureMauiHandlers 添加 AddCompatibilityRenderer , 如下所示:

    推荐阅读