52 Weeks of Xamarin: Week 11 – Customized Controls for Xamarin.Forms

2015-10-23 16:02:22来源:作者:Jesse Liberty人点击

Xamarin.Forms is a killer framework, and it has a wide variety of very flexible controls. But sometimes you run into restrictions on the control that you really need to override. The answer to this dilemma is to create a customized control.

To understand how to create a customized control, you must first understand that every control consists of an element (e.g., a button) and a renderer (the platform-specific code that tells the phone how to draw the element.

The trick to customizing a control is to override one or more methods in the renderer. To see this at work,we’re going to start very easy with a shaded button. Future postings will tackle more complex rendering.

[This blog post is based on material from my forthcoming Pluralsight course]

Normally, a Xamarin.Forms button looks more like an HTML link than like a button. This makes me slightly crazy, so we’re going to create a button that has a shaded background, so that you can see its extent.

To get started, create a new project called VisibleButton. Set up the App in the usual way to point to a main page named MainPage.xaml. Here are the steps:

Create our shaded button Add it to the XAML Write the renderer for each platform Create the Shaded Button

To create the shaded button, create a new class called (surprise!) ShadedButton. Here is the complete class,

public class ShadedButton : Button { }

Two things to notice: it derives from Button and it has no body.

Add it to the XAML

XAML has no knowledge of a ShadedButton, so you’ll have to create a namespace for this assembly and then identify the ShadedButton with that namespace,

xmlns:local="clr-namespace:VisibleButton;assembly=VisibleButton"... <Label Text="Don't press that button!" /> <local:ShadedButton Text="Click me!" TextColor = "Yellow" /> Write the Renderer

Open the iOS project and add a class called ShadedButtonRenderer. Derive the class from ButtonRenderer. The only method you need to override is OnElementChanged, which will be called each time the button needs to be rendered,

protected override void OnElementChanged(ElementChangedEventArgs< Xamarin.Forms.Button> e) { base.OnElementChanged(e); if (Control != null) { Control.BackgroundColor = UIColor.Gray; } }

Control is defined in the base class, and represents the element (the button). Here, all we’re doing is giving the button a gray background.

The Android project overrides the identical method.

The final, critical step is to link the renderer to the element. This is accomplished by using an Attribute in the platform-specific Renderer class. This attribute must be outside of any class or namespace.

[assembly:ExportRendererAttribute( typeof(ShadedButton), typeof(ShadedButtonRenderer))]

You use the same attribute on each platform.

The result is a button with a shaded background, as shown at the start of this posting.