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项目 , 预览效果 , 如下所示:
文章图片
说明:通过上面几步, 我们轻松的完成了在Xamarin当中自定义渲染器并且显示在模拟器当中 , 接下来 , 主要的任务是将Xamarin现有的自定义渲染器移植到MAUI项目中 。
渲染器移植至MAUI项目
第一步
这里 , 直接创建名为MAUIRender的新MAUI项目 。
文章图片
第二步
然后 , 我们把Xamarin中创建的MyButton与MyButtonRender直接复制到MAUI的项目中 , 如下所示:
文章图片
MyButtonRender类修改如下:
protectedoverride void OnElementChanged(ElementChangedEventArgs<Button> e){base.OnElementChanged(e);if(Control!= null)Control.SetBackgroundColor(global: :Android.Graphics.Color.Red);}}}
说明:此处更新涉及更新命名空间引用
MyButton类修改如下:
}}
说明:using Xamarin.Forms;更新为:using Microsoft.Maui.Controls;
【using|MAUI 移植 Xamarin.Forms 自定义渲染器】第三步
依赖注入自定义的Render
上面所讲到移除 [assembly: ExportRenderer(typeof(MyButton) ,typeof(MyButtonRender))] 声明 , 在Xamarin当中 , 渲染器强制声明在Android项目中 , 耦合性很强 。 这一点在MAUI项目当中 , 则是通过Startup类中依赖注入的形式添加 , 通过扩展方法 ConfigureMauiHandlers 添加 AddCompatibilityRenderer , 如下所示:
第四步
启动Android项目 , 预览效果 , 如下所示:

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

文章图片
第二步
然后 , 我们把Xamarin中创建的MyButton与MyButtonRender直接复制到MAUI的项目中 , 如下所示:

文章图片
MyButtonRender类修改如下:
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;
MyButton类修改如下:
}}
说明:using Xamarin.Forms;更新为:using Microsoft.Maui.Controls;
【using|MAUI 移植 Xamarin.Forms 自定义渲染器】第三步
依赖注入自定义的Render
上面所讲到移除 [assembly: ExportRenderer(typeof(MyButton) ,typeof(MyButtonRender))] 声明 , 在Xamarin当中 , 渲染器强制声明在Android项目中 , 耦合性很强 。 这一点在MAUI项目当中 , 则是通过Startup类中依赖注入的形式添加 , 通过扩展方法 ConfigureMauiHandlers 添加 AddCompatibilityRenderer , 如下所示:
推荐阅读
- 器官|全球首例!猪心脏移植人体
- 心脏病人|美国一男子接受猪心脏移植手术
- 猪器官|猪心脏移植给人背后有哪些科技突破
- 新浪科技综合|科普:猪心移植给人背后有哪些科技突破
- 手术|良医 | 首次猪心脏移植给人,异种器官移植时代到来了吗?
- 猪器官|科普:猪心移植给人背后有哪些科技突破
- 人物|邢台18岁女孩百草枯中毒 肺移植后已经可以下床活动
- 新浪科技综合|全球首例!人类首次接受转基因猪心脏移植,患者术后3天情况良好
- IT|美国医生为患者移植猪心脏 术后病人情况良好
- 平台|MAUI中构建跨平台原生控件实现