Xamarin.Forms uses a common API to render cross-platform mobile UIs. Therefore, the components can be rendered differently on each platform, using a renderer class. This renderer class creates a native control and translates the properties of the Xamarin.Forms control to it.
Custom renderers are used to ensure a consistency of appearance in elements across platforms for Xamarin controls like style, background color, text format, and so on.
Xamarin.Forms uses abstractions to define these elements. Then, it transforms each abstraction, offering an implementation and mechanism to each platform.
In this article, I will explain how to customize the TimePicker control with a Placeholder property to display text, since the Xamarin.Forms control does not come with this customization property.
Luckily, the native controls of Android and iOS do have this property. Therefore, we only have to extend the existing TimePicker control and create a renderer for each platform.
Let’s get started!
We will start by creating a control that inherits the Xamarin.Forms TimePicker. Then, we’ll add the desired new Placeholder property. For this, we must first create a new folder called Controls and a class named CRTimePicker inside it.
Refer to the following code.
`**using**` `Xamarin.Forms;`
`**namespace**` `TImePicker_Render.Controls`
`{`
`**public**` `**class**` `CRTimePicker : TimePicker`
`{`
`**public**` `**static**` `**readonly**` `BindableProperty EnterTextProperty =`
`BindableProperty.Create(propertyName: nameof(Placeholder), returnType:` `**typeof**``(``**string**``), declaringType:` `**typeof**``(TimePicker), defaultValue:` `**default**``(``**string**``));`
`**public**` `**string**` `Placeholder {` `**get**``;` `**set**``; }`
`}`
`}`
The TimePicker control will be added in the view where we want to display it. For didactic reasons, I will implement it in the following way in my MainPage file.
`<?``**xml**` `version``=``"1.0"` `encoding``=``"utf-8"``?>`
`<?``**xml**` `version``=``"1.0"` `encoding``=``"utf-8"``?>`
`<``**ContentPage**` `xmlns``=``"http://xamarin.com/schemas/2014/forms"`
`xmlns:x``=``"http://schemas.microsoft.com/winfx/2009/xaml"`
`xmlns:d``=``"http://xamarin.com/schemas/2014/forms/design"`
`xmlns:mc``=``"http://schemas.openxmlformats.org/markup-compatibility/2006"`
`xmlns:controls``=``"clr-namespace:TImePicker_Render.Controls"`
`mc:Ignorable``=``"d"` `x:Class``=``"TImePicker_Render.MainPage"``>`
`<``**StackLayout**` `VerticalOptions``=``"Center"``>`
`<``**Label**` `Text``=``"TimePicker with Placeholder"`
`Margin``=``"10,0"``/>`
`<``**controls:CRTimePicker**` `Placeholder``=``"Hora de Inicio"`
`Visual``=``"Material"``/>`
`</``**StackLayout**``>`
`</``**ContentPage**``>`
Now, we must create the renderer on each platform. In this example, we will be using the Visual Material, and therefore we have to inherit the renderer from the MaterialTimePickerRenderer class.
#mobile #user interface #xamarin #android #ios #timepicker