头图

Hello everyone, I am the researcher of the Microsoft MVP Lab-Zhou Hao. This article mainly introduces how to transplant the existing Xamarin CustomRenderer to use in the new MAUI project. Next, let us go to the laboratory to find out!

image.png

Introduction

As we all know, .NET MAUI uses Handler, while Xamarin uses Render mode. Although the new rendering mode is used in MAUI, it is still compatible with the custom renderer in Xamarin. This means that if your project is ported from Xamarin to MAUI, most of the code can be reused. This article describes how to use Xamarin The Renderer is ported to the .NET MAUI project.

prerequisites

In order to restore this test environment, the following describes the development environment of this test, as follows:

IDE: Visual Studio Community 2022 Preview (64 bit) 17.0.0 Preview 7.0

operating system: Windows 11 Home Edition has the Andoroid subsystem installed (for debugging)

IDE module: installs Xamarin mobile terminal development environment and MAUI preview environment

Create Xamarin renderer

first step

First create a Xamarin.Forms project, create a CustomRender folder in the Android project, and create a custom renderer MyButtonRende, as shown below:

cc7b1451177abb9a1390b3e63c67aff2.png

Description of MyButtonRender class is as follows:

using Android.Content; 
using App2.Droid.CustomRender; 
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using App2;

[assembly: ExportRenderer(typeof(MyButton), typeof(MyButtonRender))]
namespace App2.Droid.CustomRender
{
    public class MyButtonRender : ButtonRenderer
    {
        public MyButtonRender(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);
            if(Control!= null)
            {
                Control.SetBackgroundColor(global::Android.Graphics.Color.Red);
            }
        }
    }
}

Second step

Add the MyButton class to the class library project App2 and inherit Button, as shown below:


using Xamarin.Forms;

namespace App2
{
    public class MyButton : Button
    {

    }
}

third step

Use MyButton in Xaml as follows:

<ContentPage xmlns="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:MyButton Text="About!" />
  </Grid>
</ContentPage>

the fourth step

Start the Android project and preview the effect, as shown below:

4b83d2eba01e6010670bc491b519dae4.png

description: Through the above steps, we easily completed the custom renderer in Xamarin and displayed it in the simulator. Next, the main task is to transplant the existing custom renderer of Xamarin to the MAUI project. Then continue the performance below.

Porting the renderer to the MAUI project

first step

Here, directly create a new MAUI project named MAUIRender

39802fe03053a0783f10d01fb81b97e2.png

Second step

Then, we copy the MyButton and MyButtonRender created in Xamarin directly to the MAUI project, as shown below:

89b42494de01d7b7d537666bd6c7aff5.png

The MyButtonRender class is modified as follows:

using App2;
using Android.Content; 
using Microsoft.Maui.Controls.Platform;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Compatibility.Platform.Android.FastRenderers;

namespace MAUIRender
{
    public class MyButtonRender : ButtonRenderer
    {
        public MyButtonRender(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            if(Control!= null)
                Control.SetBackgroundColor(global::Android.Graphics.Color.Red);
        }
    }
}

Description: update here involves updating the namespace reference

  • Remove the old Xamarin reference:
    using Xamarin.Forms.Platform.Android;
    using Xamarin.Forms;
  • Add a new MAUI reference:
    using Microsoft.Maui.Controls;
    using Microsoft.Maui.Controls.Platform;
    using Microsoft.Maui.Controls.Compatibility.Platform.Android.AppCompat;

Remove [assembly: ExportRenderer(typeof(MyButton), typeof(MyButtonRender))] (the reason is described below)
The MyButton class is modified as follows:

using Microsoft.Maui.Controls;

namespace App2
{
    public class MyButton : Button
    {

    }
}

description: using Xamarin.Forms; Update to: using Microsoft.Maui.Controls;

third step

Dependency injection custom Render

As mentioned above, the [assembly: ExportRenderer(typeof(MyButton), typeof(MyButtonRender))] declaration is removed. In Xamarin, the renderer is mandatory to declare in the Android project, and the coupling is very strong. This point, in the MAUI project, is added in the form of dependency injection in the Startup class, and AddCompatibilityRenderer is added through the extension method ConfigureMauiHandlers, as shown below:

public static MauiApp CreateMauiApp()
        {
            var builder = MauiApp.CreateBuilder();
            builder
                .UseMauiApp<App>()
                .ConfigureFonts(fonts =>
                {
                    fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
                })
                .ConfigureMauiHandlers(handler =>
                {
                #if ANDROID
                handler.AddCompatibilityRenderer(typeof(MyButton), typeof(MyButtonRender));
                #endif
                });

      return builder.Build();
    }

description: The uses ANDROID conditions depends on us and defines a custom renderer for the IOS platform. Of course we can do this. If the renderer is only provided for Android, we can set it separately.

the fourth step

Add the MyButton namespace to the XAML page and declare MyBuToon, as shown below:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MAUIRender.MainPage"
             xmlns:my="clr-namespace:MAUIRender"
             BackgroundColor="{DynamicResource SecondaryColor}">
    <Grid>
        <my:MyButton Text="Hello,MyButton!!!"
                     HeightRequest="80"
                     WidthRequest="300"
                     HorizontalOptions="Center"
                     />
    </Grid>
</ContentPage>

The final running effect diagram is as follows:

1706e39161099adc0d152d47a4fe91ae.png

Summarize

This article mainly introduces how to port Xamarin Render to the .NET MAUI project. Of course, in the new MAUI, it is still recommended that you use the new Handler handler to implement it, and it provides better performance and flexibility .

bc93fde364ea9dd3d9106b58e805b770.png

Microsoft's Most Valuable Expert is a global award granted by Microsoft to third-party technology professionals. For 28 years, technology community leaders around the world have won this award for sharing their expertise and experience in online and offline technology communities.

MVP is a team of experts who have been carefully selected. They represent the most skilled and intelligent people, and they are experts who have great enthusiasm for the community and are willing to help others. MVP is committed to helping others through speeches, forum questions and answers, creating websites, writing blogs, sharing videos, open source projects, organizing conferences, etc., and to help users in the Microsoft technology community use Microsoft technology to the greatest extent.
For more details, please visit the official website:
https://mvp.microsoft.com/zh-cn


Welcome to follow the Microsoft China MSDN subscription account for more latest releases!
image.png


微软技术栈
423 声望996 粉丝

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。