Monday November 5th, 2018

Xamarin.Forms Custom Renderer

By Ebubekir Sezer

When we making programs, we want use different features of the objects. Maybe you want to give different features for on different platforms, For the make that we use Custom Renderers.

We can give different views to the object on different platform like iOS, Android,etc.. and that can help your project to have better design. In this project, i will give some features to the entry. Before the doing anything i update Xamarin.Forms from the nuget package manager. And then i created a class which name is CustomEntry and i take inheritance form the Entry class for my CustomEntry class. I take inheritance because i do not want to change all entry. I was went to the Android layer and i created a folder with the name of Renderer and then i create a class with the name of CustomEntryRenderer. I wrote those codes to CustomEntryRenderer;

using CustomRenderer;
using CustomRenderer.Droid.Renderer;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: Xamarin.Forms.ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]
namespace CustomRenderer.Droid.Renderer
{
    public class CustomEntryRenderer:EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
            if(Control != null)
            {
                Control.SetBackgroundColor(Android.Graphics.Color.Yellow);
                Control.SetTextColor(Android.Graphics.Color.Blue);
            }
        }
    }
}

I change the entry to my demand. Later, in the portable layer i created a folder with the name of Views and i create MainPage class and MainPage2.xaml in this folder. For these pages i use my CustomEntry. Here are the codes;

using Xamarin.Forms;

namespace CustomRenderer.Views
{
    public class MainPage : ContentPage
	{
		public MainPage ()
		{
            CustomEntry name = new CustomEntry();
            name.Placeholder = "İsminiz";
            StackLayout myLayout = new StackLayout();
            myLayout.Children.Add(name);
            Content = myLayout;
		}
	}

Xaml Codes;

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:CustomRenderer"
             x:Class="CustomRenderer.Views.MainPage2">
    <ContentPage.Content>
        <StackLayout>
            <local:CustomEntry Placeholder="İsminiz:"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

You can choose the pages to your MainPage in App class. You can reach the project with the clicking here. You can ask your questions by comments or e-mail.