.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 times 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…

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…

Xamarin forms – iOS disable cancel button on SearchBar

When you are using Xamarin forms and add the SearchBar control, you’ll notice that there will be a Cancel button shown while you are typing text in the search entry area.

We wanted to get rid of this cancel button, to get a cleaner design…
So I looked for the iOS reference on the UISearchBar and it seems that by manipulating the ShowsCancelButton property, you can show or hide that button.

To get this working I did what any Xamarin dev would do when you need to tweak native properties that are not available in Xamarin forms itself, I created a Custom renderer for the SearchBar…

The code is fairly simpel:

BUT when trying this out in a demo app, I noticed that the Cancel button would still appear when I started typing text in the search entry!!
No idea why this could be happening, I opened the Open Source code of Xamarin forms to take a look at how the guys of Xamarin are handeling the SearchBar.

And yes, thank god it’s Open Source, because now I could see why my custom renderer has no effect!
If we take a look at https://github.com/xamarin/Xamarin.Forms/blob/74cb5c4a97dcb123eb471f6b1dffa1267d0305aa/Xamarin.Forms.Platform.iOS/Renderers/SearchBarRenderer.cs#L167, we can see that the Xamarin forms base SearchBar renderer for iOS will toggle the ShowCancelButton property as soon as you change the text of the search entry… In other words, this will override my initial setting in my custom renderer.

Back to square one, how can we still hide the cancel button in this scenario?
Well if you look further in the code of Xamarin Forms, we will see that the cancel button is being updated each time the TextProperty and the CancelButtonColor property are changed.
So we need to override that behavior instead…

To do this, we’ll change our custom renderer and only add following code:

By adding this code we will bypass the base code of OnElementPropertyChanged if one of these 2 properties change. We do still copy/paste the original Xamarin forms code for the TextProperty because this is needed.
I did not however, copy over the code for the color changing of the cancel button – because want to hide it, so no need for that code in our project!

Well still not sure why the guys at Xamarin are forcing this cancel button, but great to know the code is Open Source so we can at least act upon it 🙂

Final result ( first one is the faulty renderer, second one is the correct renderer )

screen-shot-2016-10-27-at-14-51-15

All the code up on my GitHub

Xamarin forms – iOS pin entry control

** Update : there is now also a new property ClearText that will show what you entered if needed

Most apps will have some kind of login feature, passing in credentials. Often this will be done with an Entry control set IsPassword to true.

But for a project we are working on, we needed a pin code entry… In other words, let the user see how many digits he has to enter and only allow numeric values.

So something like this:

PinEntry

To accomplish this, we created our own control. It’s a grid that will draw columns for the amount you’ve assigned to the PinLength property and it will add small dots and big dots. The big dots will become visible when the user enters digits.
Some other nice properties, you are able to hook up a Command that will be fired when the user has entered all required digits, this can be used to verify the pin.
The value of the pin is available in through the Input property.
There is also a Reset method to clear the input and redraw all small dots.

Example XAML usage:

For now I’ve only added the iOS implementation, this because there is currently no easy way to auto show the keyboard on Android. But a work around is to draw your own keyboard on screen and hook up the Input property of the Pin control.

All code and sample page can be found on my GitHub here…

Anyhow, hope this can be of any use!

Xamarin forms – multi line label custom renderer gotcha

** UPDATE **

We expanded this and added an Effect for eveyone to use in the Xamarin Forms Community Toolkit!
It’s available here : https://github.com/FormsCommunityToolkit/FormsCommunityToolkit
The effect itself resides here : https://github.com/FormsCommunityToolkit/FormsCommunityToolkit/tree/dev/src/Effects/Effects/Label

On a project I’m working on, we needed a label that would show an ellipsis at the end. ( the 3 … indicating there is more text but not enough space on the screen to fit it all )

Having this on a label control in Xamarin forms is easy, you just add the property

this will force the ellipsis to appear if needed.

But on a specific page we wanted to show more text to the end user and even than add an ellipsis if needed. So in other words we would love to be able to tell the label control how many lines it should at least try to display.
To get this working in Xamarin forms you’ll need to add a custom renderer. Because the Xamarin forms label control doesn’t have any property available for us to manipulate to accomplish this.

This is not difficult at all to do, but there is a small gotcha with Android when you want to pull this off!

But let’s start with what you need to do to get this working.
In the Xamarin forms PCL ( so the general one, not the iOS or Android project ), we first add a class called MultiLineLabel.cs – this will be our own custom control.
It inherits from Label and we only need to add 1 dependency property called Lines, defined as an int. It looks like this:

After defining this custom control, we can use it on our XAML page, like so:

We will be using this Lines property in our custom renderers.
First up the iOS custom renderer for our MultiLineLabel. Create a class in the Xamarin forms iOS project called CustomMultiLineLabelRenderer.cs with following code:

You’ll notice that we are checking if the user specified a value for the Lines dependency property and if this is true, we pass this to the actual iOS UIKit.UILabel control by setting it’s Lines property. With this in place we get following result.

Screen Shot 2016-06-27 at 08.31.08

So iOS is done and looking great. Now add the Android renderer. Create a CustomMultiLineLabelRenderer.cs class in the Xamarin forms Android project with following code:

This doesn’t look all that different from the iOS counterpart… instead of setting a property we now use a method SetLines on the Android.Widget.TextView indicating how many lines we want it to display.
But wait, if we try this and look at the result, we’ll notice that it doesn’t work!!

Screen Shot 2016-06-27 at 08.31.05

It took me a while to figure this out ( I’m no Android expert 😉 ). But after taking a look in the Xamarin forms source code ( glad it’s open source 😉 ) I noticed they will always force a SetSingleLine(true) when setting the TailTruncation LineBreakMode…
Code can be seen here https://github.com/xamarin/Xamarin.Forms/blob/2d9288eee6e6f197364a64308183725e7bd561f9/Xamarin.Forms.Platform.Android/Renderers/LabelRenderer.cs#L179

So the fix is easy… you need to reset this Single Line forcing, the final code looks like this ( in your custom renderer ) :

With that in place we’ll get following result

Screen Shot 2016-06-27 at 08.31.31

Yeah success!
To start I’ve done a pull request on Xamarin forms to counter this SingleLine forcing, but not sure this will be added though… https://github.com/xamarin/Xamarin.Forms/pull/234
So better be safe and add the extra line in your own custom renderer for now.

As always example project up on github here…

Xamarin forms – multi line page title

On a current Xamarin forms project I’m working on, there came the question if it would be possible to show 2 lines in the title bar of our app instead of 1.
Normally this is not something you would do, seeing the default behaviour on iOS and Android, an app would only display 1 line and cut if off by adding ‘…’.

But in our case we are showing detail information on a conversation and it would help the user if we could show some more context.

The goal would be like this:

Screen Shot 2016-05-30 at 22.04.41

Screen Shot 2016-05-30 at 22.05.27

To achieve this result, you’ll need to implement a custom renderer on each platform. Both on iOS and Android of the type PageRenderer.

First iOS.
In your Xamarin Forms solution, underneath the iOS project add a folder called CustomRenderers and add a class called CustomContentPageRenderer.cs.
Here we will implement a PageRenderer with following code

Inside the WillMoveToParentViewController method we will grab the current page and see if it does contain an actual Title ( not each page needs one ).
If so, we’ll new up an UILabel because with this iOS control we can set how many lines need to be used ( if needed ) : titleLabel.Lines = 2.
We must ofcourse not forget to pass the current page title to it and only thing left afterwards is placing this UILabel in the TitleView of the current navigation page : parent.NavigationItem.TitleView = titleLabel.

By doing this we will override the normal Xamarin Forms rendering of the title in a navigation page and allowing use of 2 lines in it!

Secondly Android.
Same setup as in iOS, so a CustomRenderers folder with a CustomContentPageRenderer class file. But there is a bit more code needed for this to work now…

You’ll see now that we are using the OnElementChanged method to do almost the same as in iOS. So again check if the actual page does have a title or not and when it does, create a new TextView element.
On this Android control we can also indicate that we want to use 2 lines is needed : title.SetMaxLines(2).
And also here we need to pass in the actual page title and adjust the default Xamarin forms rendering view : actionBar.SetCustomView (title, new ActionBar.LayoutParams (LayoutParams.MatchParent, LayoutParams.MatchParent)).

What is different on Android, is that the ActionBar ( where the title is shown ) is shared across all pages. Thus once you’ve manipulated it, it will be fixed for all.
Meaning that when you have navigation and go back in the navigation stack, you’ll see that the set title will no longer change!
To counter this, we’ll need to hook into another event to keep track of this back stack navigation and if needed reapply the title.
This is done by monitoring the Element.Appearing event and when we enter this, reset the page title : ((TextView)actionBar.CustomView).Text = page.Title.

Hope this makes some sense and can help those out there that do need this feature 🙂

As always all the code can be found on my github right here… https://github.com/Depechie/XamarinFormsMultiLineTitle

MvvmCross UWP SplitView

With the new UWP platform to create universal windows app, we now also have a new control called the SplitView.

This control allows us to ‘split’ a page in 2 parts, a left part that is a pane, mostly used for showing a navigation menu. And a right part where we will be loading our content pages.

Microsoft has created a nice demo app on how you could set this up! To be able to load views in only the right part of the SplitView, we need to use a Frame.
Complete demo can be found here https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/XamlNavigation/cs

All good and well, but what when we want to use this setup in our cross platform environment? In other words what do we need to do in our UWP project when we are building it using Xamarin and MvvmCross? For reference we are talking about using a PCL project ( for cross platform use ) and a UWP native project using that PCL, all wired up with MvvmCross.
The basis of this setup came from this blogpost: http://stephanvs.com/implementing-a-multi-region-presenter-for-windows-10-uwp-and-mvvmcross/

We’ll only be focussing on the UWP part, because setting up MvvmCross should be ok for people who know MvvmCross 🙂
When your project is created, we’ll set up a main page where we implement our SplitView.
I’ve added a FirstView and it inherits from MvxWindowsPage, it contains the SplitView with a Frame in the content part. Import thing to note here is that we are providing a name for the Frame, called FrameContent, this will define our MultiRegion.

Nothing fancy so far. But in the code behind of this View we need to add a property called AppFrame, because that will be used later on to enable the page loading in the defined frame. So just add the following in the code behind:

Now for the actual page loading, we will need to override the View Presenter creation of MvvmCross, this is done in the Setup.cs of the UWP project. Because instead of creating normal MvvmCross views, we need a MultiRegionView.
So add the following override in your Setup.cs file:

Last thing to do is indicate what views need to be loaded inside the frame, you do this by adding a MvvmCross attribute above your View definition. So if I want SecondView to be loaded in the region, I just add the following above the class definition of the view in code behind:

This will tell MvvmCross to load the complete view in a Region called FrameContent and like we said earlier, this is the name of our Frame we definied in our FirstView.
Now each time when you navigate to this view by using the MvvmCross viewmodel navigation, it will be shown inside the frame of your SplitView!

That’s it, not that hard actually 😉
A complete demo app of this can be found on my GitHub here https://github.com/Depechie/MvvmCrossUWPSplitView