Creating a good Xamarin Forms control - Part 3 - UI Day 4
In the previous article I proposed the foundations of a win-win architecture for a good Xamarin Forms control using a multi targeting project.
Today I am presenting a way to create a control with a renderer that auto register itself, greatly simplifying the control's usage in teams, but also its documentation and its maintenance.
A multi-targeting project generates one library for each target platform (iOS, Android, ...), as if you were compiling the project for each individual platform. It is NOT a "shared project", but it contains the source code for every platform it supports. It has the MSBuildSdkExtras SDK type.
For Xamarin Forms projects, you only need to add a reference to this multi-targeting project from your netstandard project. References are transitive and the Xamarin Forms platform projects will automatically reference the matching platform library.
See the previous article for details.
I'm gonna show you 2 ways to registrer a renderer: the official and the secret way. First the official way.
A "forms" control is a class with properties and events that can be used in XAML code. For example the Label.cs class that you use in XAML like this: <Label />.
This control class is shared on all platforms (android, ios, ...). Obviously it contains only codes that can be common to all platforms. Natively, on iOS for example, it is mapped to a UILabel from UIKit. On Android its a TextView from the Android SDK.
Each mapping must be declared to the Xamarin Forms runtime. This can be done in 2 way: the official way and the secret way.
For both ways you need a class called a custom renderer, which often inherits from the platform's UI control (UILabel for iOS) and an interface. A helper class ViewRenderer<Xaml,Platform> implements the interface and can be used directly.
This can be done in 2 way: the official way and the secret way.
The official way to map a custom renderer to a xaml control is to add metadata to the assembly containing the renderer: