Xamarin.Forms - Useful String Converters for Your Text

Introduction

 
Mobile apps commonly display strings such as lable titles, documents and any kind of text. Strings could be either hard-coded in the app code, for which you might have control, but they could also come from external services such as APIs so you might need additional formatting when data-binding to the UI.
 
In this article I will share some of the converters I use in my daily work, which are very useful to satisfy some common needs.
 
I will start with the converter's code, then I will put them all together inside an example. 
 

Title case converter

 
Title-casing is when the first letter of each word in a string is capitalized, for example, "Title Case Converter". It is very common to have title-casing especially on labels that represent the title of an area.  It is very easy to format a string to title-casing using the ToTitleCase method from the TextInfo property, exposed by the CultureInfo class.
 
Here's the code:
  1. using System;  
  2. using System.Globalization;  
  3. using Xamarin.Forms;  
  4.   
  5. namespace adsStringConverters  
  6. {  
  7.     public class StringToTitleCaseConverter : IValueConverter  
  8.     {  
  9.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  10.         {  
  11.             if (value == nullreturn string.Empty;  
  12.   
  13.             string originalString = value.ToString().ToLower();  
  14.   
  15.             return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(originalString);  
  16.         }  
  17.   
  18.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  19.         {  
  20.             throw new NotImplementedException();  
  21.         }  
  22.     }  
  23. }  
Notice how the Convert method first does a conversion to lower case, which makes sense with a string that needs to be converted to title-casing.
 

Escaping new line symbols

 
More often than not, strings that an app consumes from a database contain escape symbols, such as \n for new lines. Even if views like the Entry and the Editor in Xamarin.Forms should automatically parse these symbols, it's not uncommon that this doesn't happen. You can avoid wasting time and create a converter that removes the \n (new line) and \r (return) symbols. The code is the following,
  1. using System;  
  2. using System.Globalization;  
  3. using Xamarin.Forms;  
  4.   
  5. namespace adsStringConverters  
  6. {  
  7.     public class NewLineConverter : IValueConverter  
  8.     {  
  9.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  10.         {  
  11.             if (value != null)  
  12.             {  
  13.                 value = (value as string).Replace("\\r\\n", Environment.NewLine);  
  14.                 value = (value as string).Replace("\r\n", Environment.NewLine);  
  15.                 value = (value as string).Replace("\\n\\n", Environment.NewLine);  
  16.                 value = (value as string).Replace("\\n", Environment.NewLine);  
  17.                 value = (value as string).Replace("\n", Environment.NewLine);  
  18.             }  
  19.             return value;  
  20.         }  
  21.   
  22.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  23.         {  
  24.             return null;  
  25.         }  
  26.     }  
  27. }  
The code basically replaces the escape symbols with the Environment.NewLine object that is how .NET handle a new line and carriage return in a string.
 

Using the converters 

 
Now let's build an example. Because converters are used with data-binding scenarios, the first thing to do is creating a view model class that exposes data-bound properties of type string, each assigned with some text that will be the subject of the conversion. The code is self-explanatory.
  1. using System.ComponentModel;  
  2.   
  3. namespace adsStringConverters  
  4. {  
  5.     public class StringViewModel: INotifyPropertyChanged  
  6.     {  
  7.         private string _textToTitleCase;  
  8.   
  9.         public event PropertyChangedEventHandler PropertyChanged;  
  10.   
  11.         public string TextToTitleCase  
  12.         {  
  13.             get  
  14.             {  
  15.                 return _textToTitleCase;  
  16.             }  
  17.             set  
  18.             {  
  19.                 _textToTitleCase = value;  
  20.                 this.PropertyChanged?.Invoke(this,  
  21.                     new PropertyChangedEventArgs(nameof(TextToTitleCase)));  
  22.             }  
  23.         }  
  24.   
  25.         private string _textWithNewLine;  
  26.         public string TextWithNewLine  
  27.         {  
  28.             get  
  29.             {  
  30.                 return _textWithNewLine;  
  31.             }  
  32.             set  
  33.             {  
  34.                 _textWithNewLine = value;  
  35.                 this.PropertyChanged?.Invoke(this,  
  36.                     new PropertyChangedEventArgs(nameof(TextWithNewLine)));  
  37.             }  
  38.         }  
  39.   
  40.   
  41.         public StringViewModel()  
  42.         {  
  43.             this.TextToTitleCase = "This is a label title";  
  44.             this.TextWithNewLine = "This is a long string.\n\rPlease go to a new line";  
  45.         }  
  46.     }  
  47. }  
Like any other view model class, the INotifyPropertyChanged interface implementation is necessary to make the UI refresh based on property changes, because the binding starts before the value assignment.
 
In the constructor of the MainPage.cs file, let's assign a view model instance to the Page's BindingContext:
  1. public MainPage()  
  2. {  
  3.     InitializeComponent();  
  4.   
  5.     BindingContext = new StringViewModel();  
  6. }  
In the XAML code, the user interface is very simple. We add two labels bound to the properties in the view model, plus the necessary references to the converters as follows:
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <ContentPage    
  3.     xmlns="http://xamarin.com/schemas/2014/forms"    
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"    
  5.     xmlns:d="http://xamarin.com/schemas/2014/forms/design"    
  6.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  7.     mc:Ignorable="d" x:Class="adsStringConverters.MainPage"    
  8.     xmlns:local="clr-namespace:adsStringConverters">    
  9.     <ContentPage.Resources>    
  10.         <ResourceDictionary>    
  11.             <local:NewLineConverter x:Key="NewLineConverter"/>    
  12.             <local:StringToTitleCaseConverter x:Key="TitleCaseConverter"/>    
  13.         </ResourceDictionary>    
  14.     </ContentPage.Resources>    
  15.     
  16.     <StackLayout Margin="40">    
  17.         <!-- Place new controls here -->    
  18.         <Label Text="{Binding TextToTitleCase, Converter={StaticResource TitleCaseConverter}}"    
  19.                HorizontalOptions="Center" VerticalOptions="CenterAndExpand"    
  20.                FontSize="Large"/>    
  21.     
  22.         <Label Text="{Binding TextWithNewLine, Converter={StaticResource NewLineConverter}}"    
  23.                HorizontalOptions="Center" VerticalOptions="CenterAndExpand"    
  24.                Margin="0,20,0,0"    
  25.                FontSize="Medium"/>    
  26.     
  27.     </StackLayout>    
  28. </ContentPage>     
If you now run the app, you will get the following result:
 
Xamarin.forms: Useful String Converters For Your Text
 
This is actually an easy task, but these converters will save time in the implementation.


Similar Articles