Taoffi's blog

prisonniers du temps

Xamarin forms: Don’t do modal (useless)

 

A vestige of old desktop applications UI is what is called: Modal Dialogs.

By 'Modal' we meant a 'sans-issue' place. A place where I put my user in a situation where he or she cannot go further before providing an information!

An investigation cell / A Quarantine / A Guantanamo Bay in some ways. Where I (the app developer or architect) feel secure and menacing (while pretending doing this for the end user's benefit!)… Did you say schizophrenia? :)

 

In those old days, that was an easy way for a developer to ensure the integrity of a workflow for certain key steps.

Was that wrong? Surely Yes. But lacking the means to construct an acceptable workflow integrity mechanism that can now be excusable (or forgiven).

I mean: if a workflow step may execute while it requires a previous validation that did not complete. That is entirely imputable to the application and cannot be the end user's fault.

If accessing a bank account page requires login, it is the bank account page responsibility to check if there is someone logged-in and authorized to view it (Whether we displayed a Login page or not). The fact that the Login page can be 'modal' may have a simple symbolic meaning, but at a functional level there is no sense to keep the user locked on this page or prevent him or her from doing something else (let only: cancelling!).

 

With the time going, this 'modal' vestige has proved more and more ineffective and often ridiculous. In an Internet app for instance, you cannot lock me on a modal page. I may navigate somewhere else… duplicate the navigator's tab… open another navigator, or close all and go for a beer!

In the mobile apps world that has even less sense. A mobile developer who might like these 'modal' patterns would find himself in a real battle against windmills.

 

Xamarin Forms supply a Navigation.PushModal / PopModal. But that has little sense though. Currently, the 'modal' pattern is not (at all) effective on Win Phone. In iOS, using modals often generates weird navigation situations and errors (many questions about this subject on various forums since 2014… without a final or accurate answer). In Android, modal navigation works nearly as expected, except that the OS (or the device) provides a 'back' button that allows anyone to easily exit the 'modal' prison we created for him or her!

 

So if you don't want to lose your time building strange and useless fences to keep your users in 'modal' prison cells, please don't use those Modal Push / Pop. Keep the navigation 'natural' as it is proposed by the OS. And invest more time for ensuring each step has its self-integrity mechanisms. That is a more reasonable approach.

 

Finally, we sometimes confuse 'modal' and 'full-screen' page. If you need your page to be full-screen (without the top navigation bar) that is quite easy in Xamarin Forms. Just insert this in your navigation page's constructor:

NavigationPage.SetHasNavigationBar(this, false);

Xamarin forms: Access your app resources in code

 

 

We now know how to create an App.xaml file (see this post) to define application resources.

To access these resources in xaml, we simply use {StaticResource yourResourceKey} or {DynamicResource yourResourceKey} (you can know more about StaticResource and DynamicResource, and which one to choose Here)

 

Still so often you need to access these resources in your code and that is quite simple:

You may define a static helper that can do this whenever needed:

 

public static object FindResource(string resourceKey)
{
    if(string.IsNullOrEmpty(resourceKey))
        return null;

        return Application.Current.Resources.FirstOrDefault(r => r.Key == resourceKey);
}

 

Now, you can more easily get an application resource by its key.

Let us also write a similar method that can extract this type of resource according to the OS on which the application is running using defined OnPlatform resource:

 

First a generic method that returns a per-Type OnPlatform value:

 

public static T GetPlatformValue<T>(OnPlatform<T> onplatformObjects) where T : class
{
    TargetPlatform    currentOs    = Device.OS;
    T            obj    = onplatformObjects == null
                            ? null
                            : currentOs == TargetPlatform.Android
                                ? onplatformObjects.Android
                                    : currentOs == TargetPlatform.iOS
                                        ? onplatformObjects.iOS
                                            : onplatformObjects.WinPhone;
    return obj;

}

 

Now, to get a device-dependent string defined in an OnPlatform resource with a specified key, we can write:

 

 

public static string FindOnPlatFormStringResource(string resourceKey)
{
    return (string.IsNullOrEmpty(resourceKey)) ? null
                : GetPlatformValue<string>(FindResource(resourceKey)
                    as OnPlatform<string>);
}

 

Putting these helper methods inside a static helper class would be a good thing (for all projects)!

Xamarin forms: five minutes pause!

Flood Fill a droll control

With Xamarin, you also have time to play!

Here I tried to play with a .png image file combined with a BoxView.

The .png file has some (transparent) holes…

With a BoxView (placed behind the image) and grows filling up the holes using the Animate method

 

<Grid x:Name="mainGrid" Padding="8" >
<Grid.RowDefinitions>
<RowDefinition Height="78" />
<RowDefinition Height="333" />
</Grid.RowDefinitions>

<Button x:Name="buttonStart" Grid.Row="0" Text="Start"
BorderRadius="20" HorizontalOptions="FillAndExpand"
VerticalOptions="CenterAndExpand" />

<BoxView x:Name="floodBox" Grid.Row="1" HeightRequest="0.1"
HorizontalOptions="FillAndExpand" VerticalOptions="EndAndExpand"
BackgroundColor="Fuchsia" />
<Image x:Name="img" Grid.Row="1" Source="{StaticResource imageFile}"
Aspect="AspectFill" HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
</Grid>

 

On button clicked, we start the animation:

 

private void ButtonStart_Clicked(object sender, EventArgs e)
{
    buttonStart.IsEnabled    = false;    // disable the button during animation

    double        height    = this.img.Height;

    floodBox.Animate("flood",
(percent) =>
    {
        floodBox.HeightRequest    = height * percent;

    }, 16, 10000, Easing.Linear,

// re-enable the button at animation end
(d1, d2) => buttonStart.IsEnabled = true);
}

 

 

If you would like to play with other images / animations… here is the code!

Xamarin forms: write once (and again!) – Commencement pitfalls - I

 

Intro

Xamarin approach is, without doubt, a great innovation in that it allows developers to cross platform barriers by using one same programming language. This great work started by Ximian's Mono implementation of the .NET framework on Linux. And, thus, by the .NET framework itself!

Extending Mono to be a cross platform mobile framework is a great effort and a compelling expression of the need to normalize the software development process beyond commercial competitions, ultimately for the benefit of all businesses and individuals.

Well… that is about a general view of 'what it is' and why we may use it:)

Now, to start using it is a slightly another question that often needs some craftsmanship skills and pragmatic solutions for elementary problems. Don't expect it to be that easy!

One reason for this is that Xamarin development environment is still immature and lacks many features. Its integration with Visual Studio is even too rudimentary to fulfill some usual tasks (adding a 'new item' to a project is often a tedious process… no xaml design space… Intellisense is too basic, when it works at all!). The advantages of using Xamarin forms are still so huge that it really worth trying!

With the time and adoption of the environment, these pitfalls will of course be gradually solved (at least that is what we hopeJ).

Anyway, here, I will try to list some solutions for common pitfalls I encountered when I started with Xamarin using Visual Studio (and, sometimes, Xamarin Studio). I hope my solutions for these pitfalls will soon become obsolete (the sooner, the better!). I promise then to keep them online just for History!

IDE choice: Visual Studio + Xamarin Studio…

Your IDE choice is either Xamarin Studio and/or Visual Studio (through a plug-in).

Xamarin Studio performs nicely and its xaml Intellisense (which often works!) helps avoid typo errors. At the same time it does not handle WinPhone projects. And, when run on Windows, it does not handle iOS projects neither!

In Visual Studio, with the xamarin plug-in, the project management scope is global: you manage all platform projects (the WinPhone project (of course!), Android and iOS (a connection to a Mac – with XCode installed – is required for iOS compilation))

Xamarin plug-in for Visual Studio is still a little immature. So, in Visual Studio, you may from time to time encounter issues with the Intellisense. Build action configuration does not also seem to be correctly handled by the Xamarin plug-in. We will see some solutions for these issues. Restarting Visual Studio sometime helps resolve some discrepanciesJ

It is often useful to use Xamarin Studio for some operations (build action when adding resources or xaml files is better handled than in VS plug-in)

I mainly use Visual Studio, and occasionally navigate to Xamarin Studio for some tasks. Many of the solutions mentioned here are specific to Visual Studio.

What is a Xamarin Forms solution (.sln)?

A XF solution is composed of two code areas:

  • A common PCL (Portable Class Library) project
  • A per-platform project which contains the specific platform objects, code, resources and configuration. And which references (uses) the PCL project objects, code and resources.

For a common XF solution (iMaps in the illustration), you will have:

  • The PCL library project (iMaps.dll): code and resources shared by all platforms
  • iMaps.iOS project: specific code, resources and configuration for iOS
  • iMaps.Droid project: specific code, resources and configuration for Android
  • iMaps.WinPhone project: specific code, resources and configuration for Windows Phone.

Each of these projects may, of course, reference other PCL or platform-specific libraries.

Xaml: where is the xaml design surface?

If you are new to XF, or are not posted yet: just relax, sit down, (have a beer if you can):

YOU DON'T HAVE an XAML DESIGN UI!

That is obviously a big missing link in Xamarin forms. Not only you are just abandoned to write xaml code without seeing its (potential) output, even your xaml typos get caught only at runtime (with a horrible app crash of course!)

Your options? Not so many:

You have Gorilla Player (promising and quickly evolving)… other approaches and efforts are also underway.

Gorilla allow you (at design time) to instantly preview your xaml content page (or content view) on a device or an emulator, and will catch your xaml errors and typos and tell you their exceptions details. It is also able to run simultaneously on Android and iOS (devices or emulators).

 

The application resources: the App.xaml and App.xaml.cs pitfall

It is quite useful to define a set of resources available for all objects in a project. Traditionally, in a WPF or Silverlight project, these resources are defined in App.xaml and used in other xaml files as StaticResources. If you create a WPF or Silverlight project, the project template creates two files: App.xaml and App.xaml.cs. The first is to contain the xaml resources, the second contains the application methods and properties.

When you create a new Xamarin Forms solution, your PCL project would have only an App.cs file but no App.xaml file.

To solve this:

  • Close the solution (or at least unload the PCL project)
  • Navigate to the PCL project folder
  • Rename App.cs to App.xaml.cs
  • Create a file and name it App.xaml. It should contain:


<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns=http://xamarin.com/schemas/2014/forms
xmlns:x=http://schemas.microsoft.com/winfx/2009/xaml
x:Class="
[YOUR NAMSPACE].App">
</Application>

  • Edit the project (.csproj) file (using Visual Studio or a text editor like Note Pad).
  • Change this:

<Compile Include="App.cs" />

 

  • To this:

<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>

  • Add this ItemGroup section:

<ItemGroup>
<EmbeddedResource Include="App.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>

  • Save the .csproj file
  • Reload the project (or reopen the solution)
  • Finally, in your App.xaml.cs file, you should first declare you class partial (in fact, another part is generated during compilation) the App constructor should call InitializeComponent() for your resources to be usable in other xaml files.



public partial App : Application
{

public App()
{
        InitializeComponent() ;

 

  • You can now define application resources in App.xaml and use them the same way in WPF and Silverlight apps.

Add new item: where is the ContentView (UserControl)?

ContentViews are an interesting xaml objects that are similar to UserControl in WPF/Silverlight. It allows you to define the presentation of one or more objects that you can include in other ContentPages, ListViews and other containers.

In Visual Studio, if you right click a project folder and select Add à New Item, you don't have a ContentView in the list of available items.

 

How to solve:

  • Select Add a Forms Xaml Page and give it the name you want (here: NewContentView1)
  • Open the xaml file of this new item
    • Change this

            <ContentPage xmlns=http://xamarin.com/schemas/2014/forms

  • To this

            <ContentView xmlns=http://xamarin.com/schemas/2014/forms

  • And, of course, this (end of file) </ContentPage> to this </ContentView>
  • Open the .cs file of this new item
  • Change this

    public partial class NewContentView1 : ContentPage

  • To this

    public partial class NewContentView1 : ContentView

 

This can also be done by copy / paste files and changing class names…

Craftsmanship: software is J

Files and build action pitfalls

When you add an existent xaml file to your project, it sometime just breaks the project build with many weird errors. The cause is often that the xaml file has been assigned a wrong Build action.

You should check that xaml files are assigned Build Action = Embedded Resource, Do not copy, with Custom tool = MSBuild:UpdateDesignTimeXaml.

 

 

  • Android assets: should be configured with Build Action = AndroidAsset, No copy (unless copy is needed)
  • Android Resources (& drawables): Build Action = AndroidResource, No copy (unless copy is needed)
  • iOS resources: Build Action = BundleResource, No copy (unless copy is needed)
  • WinPhone assets: Build Action = Content, No copy (unless copy is needed)
  • WinPhone resources: Build Action = Embedded Resource, No copy (unless copy is needed)

Don't use custom renderers unless…

One important feature of Xamarin forms is, obviously, to bring your forms to devices' screens. That is done by built-in 'renderers' whose role is to translate the (xamarin) xaml elements attributes to their equivalent in each platform (droid, iphone, win phone…). This translation process is not yet as perfect as we may expect. It is getting better with the progress of xamarin forms versions but, still, not yet perfect.

That sometimes produces discrepancies of graphical design between platforms (control dimensions, alignments, colors… etc.)

Fortunately, Xamarin forms provides the OnPlatform object (xaml markup extension) that allows us to specify per-platform specific values for elements and styles' attributes. And we may also use the Device static class to access information about the current platform on which your application is running and set values accordingly.

Using OnPlatform, for instance, you may define button height on per-platform value:

<OnPlatform x:TypeArguments="x:Double" x:Key="normalButtonHeight"
    Android="44"
iOS="44"
WinPhone="78"/>

Then use it in a Button style:

<Style TargetType="Button">
<Setter Property="HeightRequest"    Value="{StaticResource normalButtonHeight}" />

</Style>

 

This can also be achieved by different other methods. For instance:

  • Use the Device static class (in the PCL project) to detect and set values according to the current platform on which your application is running
  • Define specific resources (styles / templates…) in the target platform project
  • And, ultimately, you may use a 'custom renderer' (in the target platform project), to handle the graphical attributes of your UI element before it is put on screen.

The advantage of handling things in the PCL project are obvious (Write Once, Run EverywhereJ)… There are situations where this can be impossible or undesirable. In that case specific platform code or resources can be used.

With custom renderers, things are a little different though.

Xamarin framework has a set of built-in renderers for all UI elements. These renderers are evolving relatively quickly (for the better!). When you define your own custom renderer, you in fact derive yours from one existing built-in renderer and will override some of its methods. That puts a new test/maintenance hassle on your project… and, with the evolution of built-in renderers, yours may end up by performing less effectively than the built-in one… (But will still override its features).

So: think twice before going for a custom renderer!

 

(More tips and pitfall solutions to follow…!)

Xamarin forms: an image source dilemma

 

As we saw during the first 'inside-look', Xamarin exposes the Image control (or 'View', as you like) with its Source (ImageSource) that can be either a FileImageSource, a StreamImageSource or an UriImageSource.

Most of the samples that talk about how to use Image are delivered with FileImageSource… something like this:

<Image Source="photo.png" />

Or, sometimes:

<Image Source="http://company.com/photo.png" />

Great!... it looks like the Image is quite intelligent to directly know if the source is a FileImageSource or a UriImageSource… mazing work… the guys @Xamarin are quite smart and helpful… right?

Not so fast!

After having some trouble with this (you should expect some in this juvenile environmentJ), I understood something: Many (if not all) samples about Xamarin features are often delivered with the very 'trivial' situation… as they may say: for 'pedagogic' reasons (exactly the same reason we heard in primary/secondary schoolJ)

What if we were 'mature' (if not 'professional') people?... well, apparently, you do it yourself!

In the Image case is also probably accentuated by the fact that the ImageSource is a class whose base is the Element class (which is the grand-grand-parent of the Image class!)

The case

What I had to do with Image was to display an image dynamically generated by a service call. A product image for instance which you can get with an Uri that may look like:

http://mycompany.com/myService.svc?productId=123&thumbnail=1

If you try the somehow trivial cases, you simply put:

<Image Source="http://mycompany.com/myService.svc?productId=123&thumbnail=1" />

That simply 'does not work'! (please don't ask me why J)

Fortunately, we know by other experiences that software is sometimes a craftsmanship process.

I first tried using the StreamImageSource (feeding it with a stream filled up with the bytes coming from the service)… but ended up by asking myself why this object exists (it is not probably totally useless… but it was in my case!)

Image source Binding

As you now know, real life is a little different from schools.

So, as you may imagine: I in fact will not have my Image written like this:

<Image Source="http://mycompany.com/myService.svc?productId=123&thumbnail=1" />

It will rather be written like this:

<Image Source="{Binding ProductImageSource}" />

 

ProductImageSource property in this case was returning a string containing the address for getting the image. Counting on the Image intelligence for translating this address to an UriImageSource. Which did not work.

The solution (that works… and not only on my machine!)

Let us change the ProductImageSource from a string to its meaning: an ImageSource.

 

public ImageSource ProductImageSource 
{ 
    Get {    return GetImageUriSource(ProductImageUrl, 5.0);     } 
}

 

GetImageUriSource, a helper method somewhere (in a static class for instance) can do this work for products or other objects when needed:

public static ImageSourceGetImageUriSource(string strUrl, double cacheDurationMinutes) 
{ 
    if (string.IsNullOrEmpty(strUrl)) 
        return null; 

    // escape the url
    strUrl        = Uri.EscapeUriString(strUrl); 
 

    if(!Uri.IsWellFormedUriString(strUrl, UriKind.RelativeOrAbsolute)) 
        return null; 

    Uri            imgUri        = new Uri(strUrl); 

    return new UriImageSource() 
    { 
        CachingEnabled = true, 
        Uri                 = imgUri, 
        CacheValidity = TimeSpan.FromMinutes(cacheDurationMinutes) 
    }; 
}

 

That works!

Xamarin forms: elementary – don’t cast!

 

Many Xamarin users come from the Java environment and are starting with c#.

For those who don't know yet: please don't cast. Use the as operator instead.

Example:
In many situations, your method may seem like this:

void testcast(object img)
{
    Label    label1    = img as Label;    // label1 will simply be null
    Label    label2    = (Label)img;        // you get an InvalidCastException
}

 

Xamarin forms: a small step for mankind (!), an inside look - I

That is a second post in my series about Xamarin.

My intention is to write about various aspects of Xamarin environment, objects, architectural approaches as well as some recipes concluded by the lessons learnt through a year of intensive work in this platform.

 

For those who don't know about Xamarin and the Xamarin Forms offer, you may have a look at the (interesting) tale of this true modern adventure… with all the modern panoply of social experience, including unemployment and layoffs!

For a quick summary about Xamarin Forms (which is the ultimate evolution of Xamarin's offer):

Xamarin.Forms

Introduced in Xamarin 3 on May 28, 2014 and allows one to use portable controls subsets that are mapped to native controls of Android, iOS and Windows Phone.

In this post, I will try to explore important objects and mechanisms exposed in various libraries of the product. Knowledge of those is useful and may help for better understanding and usage.

Note: to explore these items, I used Visual Studio Object Browser along with Code map.

Who / What is inside?

At the root of Xamarin.Forms, two foundation objects: The BindableProperty and BindableObject.

The BindableObject (abstract class… we will see some of its genealogy later) exposes:

  • BindingContext which is simply an object
  • BindingContextProperty: a Bindable property (bounces back to the BindingContext)
  • And several events: BindingContextChanged, PropertyChanged and PropertyChanging.

 

The BindableProperty (a sealed class), exposes the following read-only properties (initialized, naturally, by several public constructors):

  • DecalringType: System.Type
  • DefaultBindingMode: BindingMode enumeration
  • DefaultValue: object
  • IsReadOnly: bool
  • PropertyName: string
  • and ReturnType: System.Type

 

Yes, with such an object, you are ready to sail far Overseas!

 

BindableObject and BindableProperty relationship

As we may expect, BindableObject makes (many) calls to BindableProperty (presumably through its BindablePropertyContext). That is a long subject that merits a specific post later. For now, let us have a look at the call mesh in the following illustration:

Exploring Xamarin Forms objects' genealogy

Who derives from BindableObject?

BindabelObject is the base class for WebViewSource à TriggerBase à Behavior à ColumnDefinition à RowDefinition à TableSectionView (what is this?J) à AND the Element!

The Element (abstract class) is the base class for à Application (!) à VisualElement (which is itself the parent of View… see below) à ImageSource (I now better understand my issues with thisJ) à GestureRecognizer à BaseMenuItem

 

Some debatable architectural aspects seem worthy for a note:

  • The Element is the base class of VisualElement.
  • In the same time, it exposes a member (ParentView) which is a VisualEement!

 

I remember, I was threatened to be fired for having used such relationshipJ. That is to say I am not fundamentally against… but let us admit that such relationship may – at least – restrain the evolution of both the parent and derived objects.

  • As you see in the figure, the ImageSource object derives from Element.
  • The Image (deriving from à View, itself deriving from à VisualElement, itself deriving from à Element)… has a member 'Source' which is an Element!

I think, at this point, I would have been definitely fired if I did something like thatJ.

But why not! It only becomes just a more risky game!

The VisualElement carrefour!

VisualElement object exposes properties needed for on-screen rendering: AnchorX / Y, BackgroundColor, Bounds, Height (get) / HeightRequest, Width (get) / WidthRequest / Minimum H/W Request, Opacity, Style, Rotation… etc. It also implements Interfaces that compose the infrastructure needed for rendering the object on each platform through the platform VisualElementRenderer<T> (where T: VisualElement).

 

The VisualElement is the base class for two objects à Page and the View.

To avoid terminology confusions (Both View and Page are translated (rendered), in Win Phone, as a Panel (Which is a FrameworkElement)), the ViewContent (derives from View) is, approximately, what is called 'UserControl' in the Windows world. A ContentPage (derives from Page), with the same relative approximation, is what we call a Window.

To better resolve (and understand) such objects associations between Xamarin core library and a specific platform, you may use Visual Studio Objet Browser (or other assembly browser) to have a look at the renderer of the Xamarin object for the platform.

The following illustrates, for instance, the View renderer object tree for the Win Phone platform.

Here, it is the Image renderer on Android platform

The Page object

The page is the root object of several Types: à The ContentPage, à the NavigationPage, à the MultiPage<T> and the MatserPage.

I personally expected the Page to be a container (of Views) and that the Content property is one of the Page Object… that is not the case (deceiving ignoranceJ).

 

  • It is the ContentPage which exposes the Content property.
  • The NavigationPage exposes the (get/set) CurrentPage member property (which is a Page… so if you would like to get its 'Content', you will have to cast it to a 'ContentPage' with the risks implied in such a cast (life is dangerous!)
  • With the MultiPage<T> (where T: Page) you again have a (get/set) CurrentPage property that returns a T (of Type Page)… you now know how to access something useful inside!
  • The MasterDetail, as you may expect, exposes a Master and Detail (each of Type Page)

 

The View object

The View is the base class of à mostly all controls and layout root classes

 

The View in everyday life

When you write <Button> in xaml (or when you write new Button(); in code), you are creating an object deriving from the View object. At runtime, your Button will be handed over to the Xamarin rendering engine to put the button on the target device's screen according to values you specified for properties of that object.

 

Note:

Not all properties are correctly transmitted or rendered on target devices (at least in the current version of Xamarin.Forms). In fact, for our Button example, some properties are not suitably tailored for all target platforms. For instance, the BorderRadius property of a Xamarin Button is not translated into anything on Win Phone.

 

The ContentView

The StackLayout example

Let us take another container control deriving from the View object: the (famous) StackLayout.

StackLayout derives from ß Layout<T>. (It is a Layout<View>).

 

What Xamarin documentation says about StackLayout:

Summary:

A Xamarin.Forms.Layout`1 that positions child elements in a single line which can be oriented vertically or horizontally.

Remarks:

Because StackLayout layouts override the bounds on their child elements, application developers should not set bounds on them.

 

It exposes two properties (Both are bindable):

  • Orientation (StackOrientation enumeration: Horizontal / Vertical)
  • Spacing (double): the spacing between the layout elements.

 

Inherited properties

  • It inherits the Children (an IList<View>) property from its base class ß Layout<T> itself implementing the IViewContainer<View> Interface.
  • Padding (Thickness), inherited from Layout
  • IsClippedToBounds (bool), inherited from ß Layout: does the container clip its children to its own bounds (see documentation remark above)
  • HorizontalOptions, VerticalOptions (LayoutOptions) and GestureRecognizers (IList<GestureRecognizer>) are inherited from ß View.
  • Deeper in the genealogy, StackLayout inherits properties of the VisualElement
    • Then from Element
      • And finally from the BindableObject (the foundation object)

 

So, when we are using a StackLayout, we are using an IViewContainer, a Layout, a VisualElement, an Element and, ultimately, using a BindableObject.

And it is often important to remember this in order to make the most effective use of an object.

The Image example

As I mentioned above, Image is another useful example. I got confused while trying to manipulate its ImageSource property.

As the name suggests, I thought that ImageSource is a 'VisualElement'… It IS NOT J. It is an Element. It has several Load methods (from File, from Stream, from Uri…) and one (get only) CancellationTokeSource property… which is described in Xamarin documentation as: Used by inheritors to implement cancellable loads). Oddly enough, none of the derived classes delivered by Xamarin (FileImageSource, UriImageSource…) make use of this Cancellation token!

Being an Element (and thus, a BindableObject), ImageSource has few properties that you can set in a PCL project (xaml / code). That maybe one of the reasons why many questions about this object are on Xamarin developers forums!

That also makes of ImageSource a good recipe area that we will explore in a later post.

 

 

In a next post, I will explore the road it takes from your xaml (or shared code) to device screen… a long journey!

Xamarin forms: a small step for mankind!

My friends at UXDivers are doing a great job in bringing Xamarin Forms into the developer's desktop with nicely crafted design and some extra facilities like their Gorilla player which allows you to instantly view your xaml output at design-time.

UXDivers' Grial U.KIT also exposes a wide range of controls and design ideas that enriches applications with ready-made and adaptable Xamarin Forms elements.

Handling fonts with Xamarin Forms

One of the interesting features of Grial is using awesome web font to create attractive buttons design with a minimal resource cost.

As fonts seem to be one interesting resource for applications and, in the same time, are handled differently in target platforms (Android, iOS and Win Phone), I did a small dive into the subject.

My conclusions so far are quite simple:

  • To use a font, in Xamarin Forms solution, you should first get its definition file (preferably a .ttf)
  • According to the platform specific project, you should place that file:
    • For Android project: in the Assets folder. Build action = AndroidAsset (no copy)
    • For iOS project: in the Resources folder. Build action = Bundled resource (no copy). The name of the font file should also be included in the application's info.plist file. Example:

      <key>UIAppFonts</key>
          <array>
              <string>Novecentowide-Bold.ttf</string>
          </array>
       

    • For Window Phone project: in the Assets folder (or sub folder of it). Build action = Content (no copy)
  • For Android: you need a custom renderer in order to apply the selected font
  • For iOS and WP: the font family name is all what you need to apply the font

 

Styles and Font family naming

As font family naming conventions vary for each platform, the ideal way is to use the Xamarin Forms OnPlatform to define this.

In this example we create an on platform string resource (in App.xaml) with the key "fontNovecentoName":

 

<OnPlatform x:TypeArguments="x:String"
    Android="Novecentowide-Bold.otf"
    iOS="Novecentowide-Bold"
    WinPhone="./Assets/Fonts/Novecentowide-Bold.otf#Novecento"
    x:Key="fontNovecentoName"/>

 We can then refer to this font family name in a Label style, like in the following:

 

<Style TargetType="Label" x:Key="labelNovecento">
    <Setter Property="FontFamily"    Value="{StaticResource fontNovecentoName}" />
    <Setter Property="FontSize"        Value="16" />
</Style>

 

Once we defined this style as an application resource, we can use it anywhere in our xaml views to create labels using the font:

<Label Style="{StaticResource labelNovecento}" Text="This should show Novencento font" />

 

That label will directly show on iOS and Windows Phone with no extra work.

For Android, we should use a 'Custom renderer' (deriving from Xamarin.Forms LabelRenderer) whose role is to extract the font family name from the xaml code and try to apply it to the target label.

 

Android custom renderer

'Custom renderers' is a vast subject. To summarize: the role of a custom renderer is to do the job of translating xaml instructions into on-screen graphical items according to each platform constraints. There is a Xamarin built-in renderer for each type of Xamarin Forms controls (Views). If you need an extra rendering job for a control, you create your own renderer inheriting the built-in one for the control… and you override one or more of that built-in renderer's methods to add your specific functionality.

 

For our subject, we need to create a custom Label renderer in Android to apply the desired font if any is specified.

Sample code:

 

 
// we should export our renderer in order to be called
[assembly: ExportRenderer (typeof (Label), typeof (iFontLabelRenderer_Android))]

namespace iFonts.Droid
{
   public class iFontLabelRenderer_Android : LabelRenderer
   {
     // override the base’s OnElementChanged
     protected override void OnElementChanged (ElementChangedEventArgs<Label> e)
     {
        base.OnElementChanged (e);

        var label      = Control as TextView;
        var  xfControl  = Element as Label;

        // try to find the font family name
        string     fontName= xfControl == null ? null : xfControl.FontFamily;

        if(string.IsNullOrEmpty(fontName))
           return;

        try
        {
           // try to create and apply the font
           Typeface font = Typeface.CreateFromAsset (Forms.Context.Assets, fontName);
           label.Typeface = font;
        }
        catch (Exception)
        {
           // throw exception if you find this useful
           //throw;
        }
     }
   }
}
 

 

 

 

 

 

 

Download the sample app. iFonts.zip (944.41 kb)