Advanced Xamarin.FormsGill Cleeren
@gillcleeren – www.snowball.be
Agenda
• Custom renderers & Effects
• Native embedding
• Behaviors
• Animations
• Drawing with SkiaSharp
• Localization
• Dependency Service
• Push notifications
Custom renderers & Effects
What’s a renderer?
• Renders a control for each
platform
• Xamarin.Forms is a collection of
renderers per platform
• Can be extended with own
renderers
• Style changes
• New controls
Xamarin.Forms rendering modelEntry
Xamarin.Forms
EntryRendererPlatform.iOS
UITextField
EntryRendererPlatform.UWP
TextBox
EntryRendererPlatform.Android
EditText
Custom RendererCustomEntry
Xamarin.Forms
CustomEntryRendererPlatform.iOS
Modified UITextField
CustomEntryRendererPlatform.UWP
Modified TextBox
CustomEntryRendererPlatform.Android
Modified EditText
DemoCreating a custom renderer
That’s a lot of work…
Enter Xamarin.Forms effects
• Small style changes only
• Limited to changing property of a
platform control
• Subclass of PlatformEffect in
platform-specific projects, then
attached to control in PCL/STL
• Can be reused
• Custom renderer can do more
• Different behaviour, overriding
methods
Xamarin.Forms effects
• PlaformEffect contains OnAttached/OnDetached methods
• Also exposes Container, Control and Element properties
• OnElementPropertyChanged is available for using the effect in combination with databinding/MVVM
Creating an effect
DEMOCreating an effect
Native embedding
Native embedding
• Allows us to use a platform-specific control
inside Xamarin.Forms
• Can be added to each control in XF that has a
Content property or Children collection
• UILabel can be added directly into
StackLayout
• Requires use of #if if used from code
• Only applicable in Shared Projects
• Works using 2 extension methods
• Add: add to Children collection
• ToView: wraps as View and sets as Content
• Extra work may be required to support correct
sizing
Using Native Embedding in iOS
var uiLabel = new UILabel {MinimumFontSize = 14f,Lines = 0,LineBreakMode = UILineBreakMode.WordWrap,Text = originalText,
};
stackLayout.Children.Add (uiLabel);contentView.Content = uiLabel.ToView();
Using Native Embedding in Android
var textView = new TextView (Forms.Context) { Text = originalText, TextSize = 14 };
stackLayout.Children.Add (textView);contentView.Content = textView.ToView();
Embedding via XAML
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:ios="clr-namespace:UIKit;assembly=Xamarin.iOS;targetPlatform=iOS">
<ios:UISwitch On="True">
DEMONative embedding
Behaviors
What’s a behavior?
• Allows adding extra functionality to a control
without subclassing it
• Will be attached to another control
• Typically, replaces code that would go in Code-
behind
• Instead, can be packaged to be reused
across applications
• Typical usages
• Effects
• Controlling an animation
• Adding a gesture recognizer
• Adding a validator option to an entry
• Linking an event of a control to a Command
in MVVM
• Even for controls that don’t support
commanding
Attached behaviors
• Static class with attached properties
• Replaced with Xamarin.Forms behaviors
public static class NumericValidationBehavior{public static readonly BindableProperty AttachBehaviorProperty =
BindableProperty.CreateAttached ("AttachBehavior", typeof(bool), typeof(NumericValidationBehavior), false, propertyChanged: OnAttachBehaviorChanged);
Xamarin.Forms behaviors
• Similar to XAML behaviors(Blend)
• Class that derives from Behavior<T>
• Override the OnAttachedTo• Don’t forget the
OnDetachingFrom to avoidmemory leaks
public class CustomBehavior : Behavior<View>{
protected override void OnAttachedTo (View bindable){
base.OnAttachedTo (bindable);// Perform setup
}
protected override void OnDetachingFrom (View bindable){
base.OnDetachingFrom (bindable);// Perform clean up
}
// Behavior implementation}
DEMOXamarin.Forms behavior
Animations
Animations in Xamarin.Forms• Simple API
• Time-based animations
• Not a XAML API
• Can be included in behaviour and be attached this
way
• Based on ViewExtensions class
• ScaleTo
• TranslateTo
• RotateTo
• FadeTo
• …
• Async API, returns Task<bool>, requires await
• Task is returned when animation is ready or
cancelled
• True when cancelled, false when completed
• Support chaining animations
Sample animation code
bool isCancelled = await image.ScaleTo (2, 2000);
await image.RotateTo (360, 2000);
Composite animations
image.RotateTo (360, 4000);await image.ScaleTo (2, 2000);await image.ScaleTo (1, 2000);
ViewExtensions class
Easing functions
• Easing class is included to include a transfer function to specify how the animations speeds up or slows down
• Included• BounceIn/BounceOut
• SinIn/SinOut
• …
await image.TranslateTo(0, 200, 2000, Easing.BounceIn);await image.ScaleTo(2, 2000, Easing.CubicIn);await image.RotateTo(360, 2000, Easing.SinInOut);await image.ScaleTo(1, 2000, Easing.CubicOut);await image.TranslateTo(0, -200, 2000, Easing.BounceOut);
DEMOWorking with animations
Drawing with SkiaSharp
Drawing with SkiaSharp
• 2D graphics system for .NET
• Open source
• Used commonly in Google products
• Can be used from Xamarin.Forms
• Vector graphics
• Bitmaps
• Text
• NuGet package:
SkiaSharp.Views.Forms
• Requires iOS 8 or later!
DEMODrawing with SkiaSharp
Localization
Using resx files
• Standard .NET approach works in
Xamarin.Forms
• Resx files
• System.Resources &
System.Globalization classes
• Device language detection is
specific per platform
Using resource values in code
var myLabel = new Label ();var myEntry = new Entry ();var myButton = new Button ();
// populate UI with translated text values from resourcesmyLabel.Text = AppResources.NotesLabel;myEntry.Placeholder = AppResources.NotesPlaceholder;myButton.Text = AppResources.AddButton;
Translating in XAML using a markup extension
<StackLayout Padding="0, 20, 0, 0"><Label Text="{i18n:Translate NotesLabel}" /><Entry Placeholder="{i18n:Translate NotesPlaceholder}" /><Button Text="{i18n:Translate AddButton}" />
</StackLayout>
DEMOLocalization
Dependency Service
Dependency Service
• Dependency Service allows resolving
platform-specific implementations in
shared code
• We can thus access iOS, Android or
WP features inside PCL/Shared
• Inside Xamarin.Forms, we have a simple
dependency resolver
• 3 parts
• Interface
• Registration
• Location
DEMODependency Service
Push notifications
Why push notifications?
• Send updates to users
• Alert users about an event when
the app isn’t running
• Trigger ‘something’ in the
background
• Get users back into your
application
Typical push notification cycle
• Several steps are required to work with notifications• Registration at app launch
• Back-end sends notification to PNS
• Maintenance
We’ll face some challenges though…• Different services (GCM, APNS,
PNS)
• Different protocols (HTTP, TCP)
• Different formats (XML, JSON)
• Scalability
• Back-end complications
• Maintenance of tokens, channels…
Hello Azure Notification Hub
• X-plat: from any back-end to any mobile platform
• No need to store device information in the app back-end (managed)
• Routing and interest groups
• Broadcast at scale, multicast
• Telemetry
Setting up an Azure Notification Hub
• One-time setup• Creation of the Notification Hub
• Registration• Clients register using PNS handle
• Register with NH using PNS handle
• Sending notifications• Back-end sends message to NH
• NH pushes to PNS
Cross-platform push
• Client SDKs for • Android – GCM/Firebase• iOS – APNS • Windows Phone – MPNS• Windows Store/UWP – WNS
• Capable of pushing to specific platform or to all at once
• Server-side SDKs for • REST• .NET• Node• Java
Sending targeted notifications
• Tags as interest groups• Client app registers with tags
• Tags are simple strings (no pre-provisioning is required)
• Back-end can target all clients with the same tag
DEMOPush notifications
Summary
• Xamarin.Forms is a powerful platform
• Getting more and more features and new SDKs added constantly
• Definitely ready for prime-time!
Thanks!
Advanced Xamarin.FormsGill Cleeren
@gillcleeren