Xamarin.Forms 3 - Cheat sheet

Posted by: Gerald Versluis , on 7/31/2018, in Category Xamarin
Views: 7955
Abstract: This tutorial gives a good overview of the most important new features of Xamarin Forms 3 in the form of a cheat sheet, and a reference on how to use them.

There has been talk around the new version of Xamarin.Forms for a while now. In May 2018, Microsoft released the new major version of Xamarin Forms, and it has great new features.

Much work has gone into stabilizing the whole thing, but that didn’t stop the Xamarin team from implementing some new features. In this article I will provide you with a quick overview in the form of a cheat sheet.

This tutorial is from the DotNetCurry(DNC) Magazine with in-depth tutorials and best practices in .NET and JavaScript. This magazine is aimed at Developers, Architects and Technical Managers and covers C#, Patterns, Xamarin, .NET Core, MVC, Azure, DevOps, ALM, TypeScript, Angular, React, and more. Subscribe to this magazine for FREE and receive all previous, current and upcoming editions, right in your Inbox. No Spam Policy.

This guide will help you have a good overview of the most important new features of Xamarin Forms 3, and a reference on how to use them!

#1. Visual State Manager

You might know the Visual State Manager (VSM) from other XAML platforms, but with version 3.0, it is now available on Xamarin.Forms. With a VSM, you can change XAML elements based on visual states. These changes can be triggered from code. This way you could, for instance, change your form layout whenever the orientation of a device changes.

A visual state, defined in XAML could look something like this:

<Style TargetType="FlexLayout">
    <Setter Property="VisualStateManager.VisualStateGroups">
        <VisualStateGroupList x:Name="CommonStates">
            <VisualStateGroup>
                <VisualState x:Name="Portrait">
                    <VisualState.Setters>
                        <Setter Property="Direction" Value="Column"/>
                        <Setter Property="Margin">
                            <OnPlatform x:TypeArguments="Thickness" Default="0">
                                <On Platform="iOS" Value="0,30"/>
                            </OnPlatform>
                        </Setter>
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Horizontal">
                    <VisualState.Setters>
                        <Setter Property="Direction" Value="Row"/>
                        <Setter Property="Margin">
                            <OnPlatform x:TypeArguments="Thickness" Default="0">
                                <On Platform="iOS" Value="30,0"/>
                            </OnPlatform>
                        </Setter>
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateGroupList>
    </Setter>
</Style>

As you can see, define a Style at the highest level and specify a target type. Inside the style, you can have different groups and a group can have states, each state defined with a different name.

These states are the key here.

In the state, you can define values for properties that refer back to the target type, in our case a FlexLayout. You can even use the OnPlatform conditions to specify different values for different platforms.

Style can be defined in the applications ResourceDictionary. Just execute this line: VisualStateManager.GoToState(Container, (width > height) ? "Horizontal" : "Portrait"); to set a certain state from code.

For example, this line of code would go to an event handler that detects if the orientation of our device has changed, and will apply the desired visual state as necessary. The “Horizontal” and “Portrait” names here refer to the names of the states we defined.

You can find more information on the Visual State Manager in the Microsoft Docs: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual-state-manager

#2. FlexLayout

Another big feature added in this major release of Xamarin.Forms is the FlexLayout.

With this new layout, you can stack and wrap child views. It works very similar to the concept you might know from CSS as the Flexible Box Layout (or flex layout or flex box).

The FlexLayout is related to the StackLayout you might already know from working with Xamarin.Forms. The big advantage of the FlexLayout is that it will wrap its children where needed. When there is no more space in the row or column where the children are defined, it will move the rest of the items to the next row/column.

A FlexLayout is very easy to define, as you can see in the code block underneath.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:FlexLayoutDemos"
             x:Class="FlexLayoutDemos.SimpleStackPage"
             Title="Simple Stack">
    <FlexLayout Direction="Column" AlignItems="Center"
                JustifyContent="SpaceEvenly">
        <!—Your controls here -->
    </FlexLayout>
</ContentPage>

Define it as any other regular layout element you are used to. With the properties you set on the FlexLayout , you can determine how to layout the children and how they should align and wrap.

To learn more in-depth about the FlexLayout, please refer to the Microsoft Docs: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/flex-layout

#3. StyleSheets (CSS)

There has been a lot of talk about implementing CSS in Xamarin.Forms. You can love or hate it, but it is available for you to use!

XAML already bears similarity with HTML so it makes sense to use CSS to apply styling .

To use CSS in your app, you need to take three steps:

  • Define your CSS
  • Add it to your (shared) project, set the build action to EmbeddedResource
  • Consume your CSS file

A simple example of a CSS file could look like the code underneath.

^contentpage {
    background-color: lightgray;
}
#listView {
    background-color: lightgray;
}
stacklayout {
    margin: 20;
}
.mainPageTitle {
    font-style: bold;
    font-size: medium;
}
listview image {
    height: 60;
    width: 60;
}
stacklayout>image {
    height: 200;
    width: 200;
}

If you are familiar with CSS, you can see it looks like the real deal and has the same capabilities. The ^ selector might seem strange since it’s not available in regular CSS. With this selector you can target a base type.

Here’s a quick overview of all selectors:

  • Type selector: specify the name of any type to target that type
  • ^ selector: select a base type
  • # selector: targets an element by name, specified with the x:Name attribute
  • . selector: select an element with a specific class, specified with the StyleClass attribute

And of course, you can select child elements in different ways.

To consume a stylesheet, there are different ways to do that. From XAML, you can reference an external file by declaring it like this:

<ContentPage.Resources>
        <StyleSheet Source="/Assets/styles.css" />
</ContentPage.Resources>

You can also define your CSS inline. To do so, do this:

<ContentPage.Resources>
        <StyleSheet>
            <![CDATA[
            ^contentpage {
                background-color: white;
            }
            ]]>
        </StyleSheet>
 </ContentPage.Resources>

There are also ways to load css files dynamically from code or interpret them from a string.

If you want to learn about all the nooks and crannies, head over the Microsoft Docs page: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/styles/css/

#4. Right-To-Left Localization

With Xamarin.Forms 3, it is now possible to apply a FlowDirection on any VisualElement, which is basically all controls. Simply call upon Device.FlowDirection to retrieve the direction of the device your user is using.

In the ideal case, you can update your app by implementing this piece of code on all of your pages: FlowDirection="{x:Static Device.FlowDirection}".

More information about RTL support is in this great blog post : https://blog.xamarin.com/right-to-left-localization-xamarin-forms/

#5. MaxLength on Entry and Editor

One of my personal favorites is a tiny addition - the new MaxLength property on the Entry and Editor control.

I might be biased because I have added this to Xamarin.Forms myself. This new version of Forms has had a lot of help from the community. Since a while now, Xamarin.Forms is open-source and on Github and they are accepting any good pull-requests you open.

Since I love Forms so much and use it all the time, I thought it would be great to contribute something back. This resulted in the addition of the MaxLength property. Using it is easy.

If you have an Entry of Editor control and you want to restrict the amount of characters that the user can enter, you can apply the MaxLength property with an integer value. This could, for example, look like this: <Entry TextColor=”Red” MaxLength=”15” />. This will cause an Entry that shows its characters in red and limits the number of characters to a maximum of 15.

The MaxLength property is bindable, so you can bind a value to this to make it more dynamic.

Other properties that were added are ProgressBar.ProgressColor, Picker.FontFamily and much, much more.

Final thoughts

The new version of Xamarin.Forms brings a lot of new goodies while also focusing on stability. Major additions like CSS, the Visual State Manager and Left-To-Right support were long due, and a lot of devs were waiting for it.

Also, community contributions are precious. If you have worked with Xamarin.Forms before, you might know there are a lot of small features and visuals you wish would just be there.

The team at Xamarin has heard you and is now taking on this challenge working together with us. A lot of great things are added already, and I am sure much more will come.

You can see all the release notes associated with this release on this page here: https://developer.xamarin.com/releases/xamarin-forms/xamarin-forms-3.0/3.0.0/ and if you look, you will notice that the first 3.1 prerelease versions are on there, so you get to take a peek into the future!

I hope this article/cheatsheet has given you a good overview of what is new and provided you with a quick-start on these new features.

This article was technically reviewed by Mayur Tendulkar.

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Gerald Versluis (@jfversluis) is a full-stack software developer and Microsoft MVP (Xamarin) from Holland. After years of experience working with Xamarin and .NET technologies, he has been involved ina number of different projects and has been building several apps. Not only does he like to code, but he is also passionate about spreading his knowledge - as well as gaining some in the bargain. Gerald involves himself in speaking, providing training sessions and writing blogs (https://blog.verslu.is) or articles in his free time. Twitter: @jfversluis Email: gerald[at]verslu[dott]is . Website: https://gerald.verslu.is


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook