Xamarin Forms – MVVM binding translated Enum values

I once did a post about how to bind Enum values and use translation in the beginning of Windows Phone development… But seeing several questions on Stack Overflow about it in other programming environments, let me work this out again using Xamarin Forms this time.

So the general idea is, that in some sort of data entry page, you want the user to be able to select a value from a list. This list contains several items, all based on a given Enum you defined.

The Enum defined in this example is very simpel, it could be used to let the user pick a t-shirt size…

Of course straight up displaying the Enum values to the user would often not be ideal, you want to format them into some readable text. Also maybe your app needs to run globally, so potentially translations will be needed.
Best way to tackle this, is by using Resource files in Xamarin Forms.

How you deal with translations and Resource files ( resx ) in Xamarin forms is very well documented here https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/localization/text. So best to go through that first before continuing here.

To make my example with enum translation work, we need a format that we will use for the keys of our values inside the Resource files. In this repository I went for the combination of {Enum type name}_{Enum value}.
Resulting in following Resource files content.


When using Resource files correctly, we will have a generated class called TranslationResources available that we can use to retrieve translated values.

After this, we are going to set up our data representation. We would like to have our CollectionView automagically binded to our Enum, in such a way that it will use the translated Enum display values instead of the corresponding Enum values. The Page xaml for it would be

The thing to notice in here, is the fact that the ItemsSource of the CollectionView is binding to a .Net Type instead of some actual data collection.

To get values displayed, we of course need to convert that type to something the CollectionView can understand, hence the use of a Converter.
The code of the Converter looks like this

The input parameter for the Converter should be a .Net Enum type, so we check if that is the case. If so we get all the values of the given Enum and pass those items through the auto generated TranslationResources class to get the correctly translated display value for the each Enum value. In the end we transform this to a List so the CollectionView can use this for displaying.
Another thing to note, is that we als keep track of the Enum index. We will need that later on to verify which item was selected in the list.

Once the list is presented to the user, we again want to capture the actual Enum value, because that would be the value we need to store in a database or pass to an API. The SelectedItem binding of the CollectionView will take care of this!

Once an item is selected we use the index that is passed along to get the real Enum value, for presenting it on screen I .ToString() it. But that would not be needed if you just want to store the value.
Of course you could also just put the original value inside the EnumItem class instead of using the index…

The result would be as follows and as always the code can be found on my GitHub…

Xamarin Forms – iOS floating tabbar

Sometimes the design of our apps requires us to create custom elements inside of Xamarin Forms.
One thing I wanted to try out, was using a floating tabbar instead of a bottom fixed one.

The end result should be this:

Let me show you how you can achieve this in Xamarin Forms targeting iOS.

We actually don’t want to create our own page panel switcher or view host, rather, we would love to reuse the current TabbedPage that is provided by Xamarin Forms. So if we want to alter the one given by Xamarin, we need to create a Custom Renderer for it.
In this custom renderer we will be hide the default TabBar that is provided by iOS and instead we will load a Xamarin Forms ContentView and place it inside the UIView that is currently loaded; placing it somewhere on the bottom of the page.

Meaning we need to convert the ContentView to a iOS native control! This is possible all thanks to Michael Ridland his code shown here https://michaelridland.com/xamarin/creating-native-view-xamarin-forms-viewpage/

The end result Custom Renderer looks like this:

Now that our view is visible and the default tabbar is hidden, we only need to trigger the actual tab switching.
This is done inside our ContentView!
Inside of the new TabBar view, we have defined 3 buttons. Each button will trigger a page switch, doing this through use of the Xamarin Forms Tabbed Page. We just switch the CurrentPage property of the TabbedPage and this will trigger the normal tab switching.

That is basically it!
As you can see the overlay tabbar is just XAML, so you can do whatever you want in it… of you would like to animate the selection or use images, you can just change it.

The end effect is like so:

As always the code can be found on GitHub here…

Xamarin forms – Switch custom font on Style Trigger

Just a small reminder for myself.
I was actually unaware this was possible in XAML styling, but now that I know it can be done, I will be using this more often 🙂 !

So assume you want to use a custom font in your Xamarin Forms app and you want to preset each Label control with it, you can define this in a Styles.xml like so:

But what do you do when your custom font has no build in Bold feature and you have to rely on a separate custom font for that?
Well, you can let your XAML style check for a trigger and swap the font!
It’s fairly easy, so the code will now look like:

And now each time you add the FontAttributes=”Bold” property to your Label control, it will use the correct font type!

Happy coding.

Xamarin forms – UWP fix listview grouped header height problem

When UWP comes into play with Xamarin Forms, you’ll notice that several default control settings are often not resulting in a pleasing UI.

One that caught my eye recently was the way the height is set in a grouped lisview header.
So assume following setup, you define a listview and enable grouping. With that you would like to control what is being shown in the header, so you define your own GroupHeader Template. Inside the template, you only need a small display area, so for demo purpose we will only enable a Label control, but are setting it’s height to a fix amount of 25!
Complete XAML look like this:

When this is done you’ll get the following layout on iOS ( I added background colours to show off the different templates and their heights ).

So everything is looking ok in reference to what we defined in XAML, but now let’s look at UWP…

Well this is odd! Somehow the height of our headers is larger than what we defined… looks like UWP has some default rendering that overrides what we have set.
So after some digging through the source code of Xamarin forms, I’ve not found any special setting that could trigger this. In other words it’s not something Xamarin does to the UWP rendering of the listview.
This meant I needed to go look at the default template settings of the UWP control itself. What I found was that the listview control has a special header template style defined that uses a specific value for the minimum height for the ListViewHeaderItemMinHeight!
It’s set to 44… this explains our weird look and feel on UWP.

The definition for this style can be found here…

With this in mind it’s actually very easy to fix this in our app. All we need to do is provide a better minimum height value for the given style key.
When using UWP in Xamarin forms, you do this sort of overrides inside your App.xaml file by defining a theme resource dictionary and adding the same key like so:

With this in place our UI will finally look like the same as the iOS counterpart.

As always the example can be found on my github here…

.Net Standard 2.0 create Microsoft Office documents in Xamarin Forms

We had to wait a while for it to happen, but it’s finally here; .Net Standard 2.0 support in Xamarin Forms.
This is a big step in sharing .net code across multiple platforms while able to target a wide range of APIs.

To show of the power of this, let’s do a fun example.
Wouldn’t it be nice if you could create Microsoft Office Excel of Word files on the fly inside your Xamarin Forms app? Of course you could offload this to a backend service, but that means you also need to be the owner of the data service. On the other hand creating simple CSV files that are compatible with Excel is also a possibility, but you are limited to only adding data in that case ( no formula’s or formatting ).

Thanks to .Net Standard 2.0 we can now use the full Office OpenXML SDK inside our Xamarin Forms apps!

First things first, how do we create a Xamarin Forms app with a .Net Standard 2.0 lib instead of a PCL.
To accomplish this now ( without any new Visual Studio templates ), just create a new blank PCL Xamarin Forms app.
When this is done, add an extra project but this time select a .Net Standard Library. You’ll get a popup window for selecting which version of .Net Standard you want to target, select Version 2.0!

If you don’t see version 2.0 yet, that means that you still need to install the new .Net Core 2.0 SDK. For using it on a Mac goto https://www.microsoft.com/net/core#macos.

When the project is inside your solution, first delete the class1 file and add the Xamarin Forms nuget package ( at least v 2.4.* ) and when that is done, just drag and drop the PCL files over to your new .Net Standard library.
Now you can just delete the old PCL project.
Reference the .Net Standard lib in your iOS and Droid projects and you are good to go.
For our example we also need to add the OpenXML nuget package so that we create and manipulate Docx and Xlsx files.

Let’s assume you have some data in a local database of pulled down from a REST service, it’s nicely presented on your screen and you can annotate and filter it.
When you are done you want to transfer this set over to some coworker but he is working in another environment and excel would suit better.

So how do we create an Excel file with this data blob?
Let me show you the code

The key element from the OpenXML SDK is the SpreadsheetDocument class, this allows us to generate a new empty Excel file! After that it’s only a matter of adding a new sheet and giving it a name.

When this is done, we still need to add data… this can be accomplished with following code

I’ve created a separate method for inserting data into an existing Excel file ( in our case the one we just created with the code previously shown ).
This method uses a class called ExcelData it’s nothing more than a simple POCO with string lists… one for the headers and the rest for the data.

Once the data is passed to the method, we’ll open up the first Worksheet available in our Excel file and inject data rows. Each row will get a set of Cells, in which we put our string data.
In this example I made it very straightforward and didn’t do any fancy Excel stuff… but now you have the basics of how to handle OpenXML files! If you go through the SDK docs, you’ll see that there is a lot more available.

Now that we have our filled up spreadsheet, we want to be able to share it. This can be done through platform specific code… for iOS we need to use a UIDocumentInteractionController

When this is used, you’ll be presented with an Open with popup where you can select different applications that are installed on your mobile device.
If Excel is installed you can actually see the generated file!

The code is available on my GitHub here…

Xamarin Forms – RepeaterView

Back in the day there was this great open source lib called XLabs that targeted Xamarin Forms.
It had a lot of nifty controls and custom renderers to fix several pain points while developing for Xamarin Forms.
But Xamarin Forms evolved and XLabs was not maintained as regular anymore and it now seems to be stranded at a dead end.

BUT, even though the code targets an older version of Xamarin forms, it doesn’t mean that there is no longer any value in it.
I’ll give you an example: the RepeaterView.

This is a nice control that helps you ‘repeat’ data elements without actually using a ListView, this can be handy if you just want to show an iteration without any possible user interaction, or if you want to be able to show all items in the collection and control your own scroll region.

Whatever the reason, XLabs had us covered and we can still use it today!

So let me show you an example of how I needed to use it on a recent design issue I had.
I needed to present data grouped, but in 3 levels. Meaning, we have a bunch of payment transfers and they are grouped in ‘signed’ and ‘unsigned’ groups, but inside those main level groups we again need to group the transfers per user account. With each account listing the transfer items with their details…

In short, this would not be doable straight out of the box wit general ListView grouping. You could just put 2 ListViews on the page, but that would not help the UI. Because we want the user to be able to scroll through 1 list with all the data in it.

There are possibly several ways of fixing this, but I went for the use of RepeaterView in combination with a grouped ListView.

First let me show you what we are going to build ( don’t judge the layout 😉 )

To achieve this we need following models

Transaction and Account class, are the real data holders and we added GroupedTransaction and GroupedAccount to be able to actually group the data and use it for the grouped ListView.

Next up the RepeaterView, I modified the XLabs version so it would work in our newer Xamarin Forms environment, but do note that my version is also stripped down to the bare minimum that I needed for this UI.

The RepeaterView takes a generic T that is being used for the items enumerator. We need to keep that in mind when we write our XAML, because this has to be supplied there.
Other than that this control is very basic, you need to give it an ItemsSource and an ItemTemplate and it will use those to build the UI.
There is also an extra option to add a HeaderTemplate, if you want some text on top. But this isn’t used in this demo.

For the actual UI we need following XAML

We are using a grouped ListView for creating the first and second data level, in our case the signed and unsigned transactions are mapped with the ListView GroupHeader, the account information is used in the ItemTemplate.
But also inside of the ItemTemplate we are using our RepeaterView to show the transactions.
This will give use 3 levels of information that are all repeatable.
Note the use of x:TypeArguments=”models:Transaction” on the RepeaterView, that’s the way to pass data to your model. This will be used for the type T of the RepeaterView.

As always a complete demo can be found on my GitHub here…

Xamarin forms Tabbed page – UWP with images

When developing cross platform apps with Xamarin forms, you’ll notice that your apps will look and feel right at home on each OS. This because the nice people of Xamarin render each Xamarin forms control as a native control with the needed control properties all filled in.
You can still tweak some of these properties when they are leveraged through the Xamarin forms control abstraction or use custom renderers and effects to get down to the native control layer.

Most of the time this is all working great, but when you try to take UWP into account, you’ll notice not everything works straight out of the box.
Hence this blog post, showing you how you can hack the current TabbedPage implementation of Xamarin forms for UWP to enable pivot headers with images!

If you’ll use following XAML in Xamarin forms, you’ll get a nice Pivot control in UWP

But when you run the app, you’ll notice that on UWP nothing is happening with the Icon property of the NavigationPage

While on iOS you’ll get something like this

So what gives? Well, the current Xamarin forms tabbed page implementation will not take into account this Icon property and ignore it during rendering.
Reading the guidelines from Microsoft, it’s recommended to actually do use icons for pivot headers if possible, read on it here https://docs.microsoft.com/en-us/windows/uwp/controls-and-patterns/tabs-pivot.
The result should be something like this

Now let me show you a hack / workaround to get the same result on UWP. I stress hack, because of the current TabbedPage implementation in Xamarin forms there is no direct way to handle this.

Searching for a solution, I needed to open up the source code of Xamarin forms, fortunately it’s open source 🙂
If you go to the TabbedPageRenderer that is used for UWP, you’ll see that a specific XAML style is used for the Pivot control. This style is called TabbedPageStyle!
Setting the style is done here https://github.com/xamarin/Xamarin.Forms/blob/4e83b8ee0fa9274a1183ca41117eb91df825e341/Xamarin.Forms.Platform.UAP/TabbedPageRenderer.cs#L148
And the actual Style can be found here https://github.com/xamarin/Xamarin.Forms/blob/8c5fd096945301a2db0d85baf77ce46812a8d89f/Xamarin.Forms.Platform.UAP/TabbedPageStyle.xaml

To create a working solution, we need to change the HeaderTemplate that is specified inside that TabbedPageStyle. Normally we would just drop in a new Style with the same name inside our UWP App.Xaml file to override the one from Xamarin forms. But due to how Xamarin forms is initialised during startup this won’t work. So a small interception has to be made to get this going.

Add a new Styles.Xaml file in your UWP project and add following Style element to it

This will enable the use of the Icon property that we have set in our Xamarin forms xaml for each tab of the tabbedPage. Only thing left is swapping out the current HeaderTemplate and using ours.
So be sure to tell UWP we have this Style in our ResourceDictionary by adding it in the App.Xaml

After that, open up the App.Xaml.cs file and look for the Xamarin.Forms.Forms.Init(e); line.
Below it add an extra line of code to do the actual Template swapping

Like I said this is a hack… but it works perfectly 🙂 instead of using the default Xamarin forms TabbedPageStyle inside the Pivot header template we’ll now be using our own TabbedPageStyle2.
Only one small detail remains, you’ll notice I added a converter inside the Style. This was needed because the Icon property on the NavigationPage of Xamarin forms maps to a FileImageSource but that is not processable straight away as a source value for the Image control inside UWP.

The converter will get the File property of the FileImageSource and return that as a valid source. With this in place you’ll get the correct image shown!

Now if you have done everything right, you’ll get the following result, a Pivot control for a TabbedPage with images on UWP

As always a complete demo solution can be found on my Github here…

Xamarin forms – custom ListView separator without BoxView

Here is a small alternative way to add your own ListView separator, without adding a BoxView inside your ItemTemplate.

This is a request often seen because the default iOS rendering of the separator is not full width, even though most apps today would generally show a full width separation.

Example before and after the code changes

Let’s start out with our regular XAML that would generate the original ListView shown on the left above.

Nothing all to special, we have a ListView hooked up with an ItemsSource and are using that together with an ItemTemplate to design the list items.
Because this is just a default implementation of a ListView we are seeing separators on iOS that are not full width.

To get a good separator we need to adjust our XAML!
First disable the default separator, this is done by adding following property to the ListView XAML

After this, wrap the complete ViewCell content inside a double StackLayout! I know this sounds like overkill but this way you’ll not run into any BoxView issues regarding margins inside the ViewCell… or other stuff.
The first StackLayout should have a BackgroundColor set to the colour you want your separator to be, the second StackLayout should have the same BackgroundColor as the rest of the container it is in… in our example the page and that is set to white. Be sure to also add a Margin to the bottom of this second StackLayout because that will represent the thickness of our separator!

Giving us following XAML

With that in place, you’ll get the same visual result as the preview image at the top right of this blog post.

As a bonus, you could omit one of the StackLayouts IF your page has a background color other than white. Because if this is the case, you can use that color as the separator color by playing with transparency inside the ListView.

Example of this, note will only work if the page itself also has a BackgroundColor set to Olive!

All code is up on GitHub here…

UWP – iconfy your design ( yep no SVG ;) )

So, been seeing a lot of SVG support being introduced into UWP to get vector images. I love this evolution, but somehow I still love how fonts work and mostly I still go that route if I need some icon representation inside an UWP app.
Fonts also easily scale, by setting the font size, what often results in better outlining with text being set on the same size! Adding color is also no problem and depending on what library you are using there is often also a full filled version as an outlined version available for a given icon.

So let me show you this alternative way on how you can use a great open source icon library to good use inside your UWP apps, through their available font.

First up go to this great icon library called Material Design Icons, here select the Download button and in the popup window select the Download the webfont button. This will contain the materialdesignicons-webfont.ttf that we will use in our UWP app.
To use it in your app, place the TTF inside your Assets folder.

Now that you have the font as an asset, you’ll still need to enable its usage in xaml. To do this, we’ll first add a reference to the font in a ResourceDictionary.
Add following entry in your resource dictionary :

Important note : the code reference should have the correct font name, otherwise it will not be visible…

After this, we are able to use it in our app, I tend to predefine some TextBlock style with default values so I can reuse these throughout my code.

Now that the style is available for any TextBlock you want to use, we can add those in our UI.
For example if you want to add an expand symbol to an image to indicate the user can enlarge it, we just select a good icon from the font and place a TextBlock inside a button on the image.
Now the most difficult part is actually getting hold of the actual text representing a given icon.
To get this, you’ll need to install the TTF in windows ( right click on the font and select install ) and use the Windows Character Map tool to copy the value.

Select a given icon and press copy to get hold of the actual value


Only thing left to do is define an button and add a TextBlock to it with the font value.
Note : in the code preview below this will not be shown because the font value can not be rendered. But inside visual studio you will see a ? representation.

If everything is added correctly you’ll be presented with a nice icon button.


As ever this code is available on my GitHub here…
Happy coding and yep SVG is good but not always needed 🙂

Xamarin forms – Clear entry control effect

When using the Entry control of Xamarin forms, we don’t have a standard fast way to let the user clear his typed in text.

It would be nice if we could add a Clear icon on the right side of the entry control that clears the current text when tapped.
Example Android and iOS:

Android previewiOS preview

Let me show you how this can be done with an Effect for Xamarin forms!

Do read up on how to create effects in Xamarin forms here…

First iOS, because this is actually the easiest to implement.
In your iOS project add a folder called Effects and in it add a new class file called ClearEntryEffect.cs.
The code for this file is as follows

In this effect, we just get hold of the UITextField native control of the Entry and adjust the ClearButtonMode property to UITextFieldViewMode.WhileEditing. This is possible due to the fact that the iOS UITextField actually has this feature build in, we only need to trigger it.
So one down, one more to go…

Android is a bit trickier, because the native EditText control does not have this pre build in, in other words we need to add this ourselves.
Again add an Effects folder, but now in the Android project and again add a ClearEntryEffect.cs class file.
The code for this one looks like

The code is not all that different, we just need to add some extra tweaking…
First, we add a Clear icon on the right side of the EditText control, this can be done with the editText.SetCompoundDrawablesRelativeWithIntrinsicBounds method on the EditText control.
You add a correct resource id to the correct position, we want it to the right hand side, so it needs to be the third parameter.
Secondly we are going to add a touch listener to the EditText control, using the SetOnTouchListener method.
In this touch listener, we verify if the EditText control is being tapped, MotionEventActions.Up, if so we verify what the actual position was where the user has tapped. If this location is anywhere inside the region of the right drawable, we clear the text of the EditText control.
You get the actual position from the touch event through the event arguments, e.RawX and we calculate the position of the drawable and compare these two values: e.RawX >= (editText.Right – editText.GetCompoundDrawables()[2].Bounds.Width())

So that wasn’t that hard, only needed to read up a bit on Android because I’m still a novice on this one.

After adding these 2 effects, only thing left to do is use them in your Xamarin forms pages!
Thing to remember here is that you still have to create a dummy class in the PCL as well… so add a class file called ClearEntryEffect.cs inside the PCL with following code

And when this is all done, you can use it in your xaml as follows

As always everything can be found on my GitHub here…