String Formatting in Xamarin.Forms  

 String Formatting in Xamarin.Forms   

Introduction

Every single app possesses a settings screen, facilitating several tiny preferences, open-source license information, program version information, Fingerprint authentication in the app, etc.

The string formatting covers the code-specific formatting of various types of objects. Along with the values of text that are being formatted, we can add other text also.

String formatting is very efficient when we are displaying strings in code format and the tool used for it is String. Format method and it’s a static method.

Occasionally, it is appropriate to display data of string format of any object or value using Data Bindings.

StringFormat Property

It is a facility that is forwarded into data bindings.

We set the StringFormat property of the Binding markup extension to a standard .NET standard which formats string with one placeholder.

<Slider x:Name=”sldr” />

<Label Text=”{Binding Source={x:Reference sldr}, Path=Value,

StringFormat=’The slider value is {0:F4}’}” />

  • Note that the string that is being formatted is written inside single quotes (Apostrophe).
  • It is done so because the XAML parser doesn’t get confused to treat the curly brackets as some other XAML’s markup extension.
  • Else, the formatted string will be treated in a similar way in which we display the floating-point value as a call to String.Format.
  • When the target property is the string type then and then only, StringFormat property will work out.
  • As data binding is complex and convoluted, when we debug those data bindings, we can add a label that displays some interposed results of the XAML file with the StringFormat.

<?xml version=”1.0″ encoding=”utf-8″ ?>

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

xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”

x:Class=”App1.StringFormatting”

xmlns:sys=”clr-namespace:System;assembly=netstandard”

Title=”String Formatting”>

<ContentPage.Resources>

<ResourceDictionary>

<Style TargetType=”Label”>

<Setter Property=”HorizontalTextAlignment” Value=”Center” />

</Style>

</ResourceDictionary>

</ContentPage.Resources>

<StackLayout Margin=”10″ BackgroundColor=”CadetBlue”>

<Label Text=”String Formatting in Slider Control” TextColor=”GreenYellow”

FontSize=”Subtitle”/>

<Slider x:Name=”sldr” />

<Label Text=”{Binding Source={x:Reference sldr}, Path=Value,

StringFormat=’The value in slider is {0:F4}’}” />

<Label Text=”String Formatting in Time Picker Control” TextColor=”GreenYellow”    FontSize=”Subtitle”/>

<TimePicker x:Name=”timePckr” />

<Label Text=”{Binding Source={x:Reference timePckr},Path=Time,

StringFormat=’The TimeSpan is {0:c}’}” />

<Label Text=”String Formatting in Entry Control” TextColor=”GreenYellow” FontSize=”Subtitle”/>

<Entry x:Name=”entry” />

<Label Text=”{Binding Source={x:Reference entry},Path=Text,

StringFormat=’The text in the Control is &quot;{0}&quot;’}” />

<StackLayout BindingContext=”{x:Static sys:DateTime.Now}”>

<Label Text=”String Formatting in Label Control for Date”        TextColor=”GreenYellow” FontSize=”Subtitle”/>

<Label Text=”{Binding}” />

<Label Text=”{Binding StringFormat=’The Long Date is {0:D}’}” />

</StackLayout>

<Label Text=”String Formatting in Label Control for Decimal No.” TextColor=”GreenYellow” FontSize=”Subtitle”/>

<StackLayout BindingContext=”{x:Static sys:Math.PI}”>

<Label Text=”{Binding}” />

<Label Text=”{Binding StringFormat=’PI to 4 decimal points = {0:F4}’}” />

<Label Text=”{Binding StringFormat=’PI in scientific notation = {0:E7}’}” />

</StackLayout>

</StackLayout>

</ContentPage>

  • The Slider and TimePicker control’s bindings express that the format specification is used for particular Double and TimeSpan datatypes respectively.

<Slider x:Name=”sldr” />

<Label Text=”{Binding Source={x:Reference sldr}, Path=Value,

StringFormat=’The value in slider is {0:F4}’}” />

  • Here in slider control’s string formatting, the {0,F4} displays the 4 digits after the decimal number.
  • The entry control’s StringFormat illustrates that how we can use double-quotes in string formatting by using HTML’s &quot;
  • The first label binding of the next StackLayout is defined with no properties and simply displays BindingContext’s DateTime value using default formatting and it is used to set an x:Static extension that has the reference to DateTime.Now property.
  • And the last StackLayout consists of the ContextBinding to the Math.PI values, that display the default values of two different numeric types.
  •  Image: Output for different String Formats

Image: Output for different String Formats

  • ViewModel and String Formatting
  • When we use a label with StringFormat to display the value of any view that’s the target of a ViewModel.
  • Either from the View page or the ViewModel page, the binding of the label can be done.
  • Normally, we can use the ViewModel method for binding because it always verifies that the binding is appropriately functioning or not between the View and the ViewModel.
  • The first way to demonstrate its use is the Color Adjustor (Opacity) example, which uses the same ViewModel as that of the Simple Color Adjustor Selector.

<?xml version=”1.0″ encoding=”utf-8″ ?>

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

xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”

x:Class=”App1.StringFormatting”

xmlns:sys=”clr-namespace:System;assembly=netstandard”>

<StackLayout Padding=”10, 0″>

<Label x:Name=”label”

Text=”Xamarin”

FontSize=”50″

HorizontalOptions=”Center”

VerticalOptions=”CenterAndExpand” />

<Slider x:Name=”sldr”

VerticalOptions=”CenterAndExpand”

Value=”{Binding Source={x:Reference label},

Path=Opacity}”  />

<Label Text=”{Binding Source={x:Reference sldr}, Path=Value,

StringFormat=’The value in slider is {0:F4}’}”

HorizontalOptions=”Center”

VerticalOptions=”CenterAndExpand”

FontSize=”Body”/>

</StackLayout>

</ContentPage>

  • This function can be easily understandable using an example of the Text Opacity program.
  • Here, the present is the pair of Label and Slider that are attached with each other only.
  • The label has the StringFormat property which displays the value of Slider present.

String Formatting in Xamarin.Forms

Image: Output for Opacity of Text

  • Another example is the Better Color Selector and it also uses the same ViewModel as that of Simple Color Selector.

<?xml version=”1.0″ encoding=”utf-8″ ?>

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

xmlns:x=”http://schemas.microsoft.com/winfx/2009/xaml”

xmlns:globe=”clr-namespace:System.Globalization;assembly=netstandard”

x:Class=”Blog.StringFormatting”>

<ContentPage.Resources>

<ResourceDictionary>

<Style TargetType=”Slider”>

<Setter Property=”VerticalOptions” Value=”CenterAndExpand” />

</Style>

<Style TargetType=”Label”>

<Setter Property=”HorizontalTextAlignment” Value=”Center” />

</Style>

</ResourceDictionary>

</ContentPage.Resources>

<StackLayout>

<StackLayout.BindingContext>

<local:HslColorViewModel Color=”Fuscia” />

</StackLayout.BindingContext>

<BoxView Color=”{Binding Color}”

VerticalOptions=”FillAndExpand” />

<StackLayout Margin=”10, 0″>

<Label Text=”{Binding Name}” />

<Slider Value=”{Binding Hue}” />

<Label Text=”{Binding Hue, StringFormat=’Hue = {0:F3}’}” />

<Slider Value=”{Binding Saturation}” />

<Label Text=”{Binding Saturation, StringFormat=’Saturation = {0:F3}’}” />

<Slider Value=”{Binding Luminosity}” />

<Label Text=”{Binding Luminosity, StringFormat=’Luminosity = {0:F3}’}” />

</StackLayout>

</StackLayout>

</ContentPage>

  • Here, present are three pairs of sliders and labels that are bounded with each other and to the same order as the source property in the HslColorViewModel object
  • The only difference between them is that the label in the Xaml file has some StringFormat property for displaying the value of each slider.
  • To display the RGB (Red, Blue, Green) color values in the three-digit hexadecimal format, there are two ways.
  • First is, we can calculate the integer values inside the ViewModel of the color components and revealing them to the properties.
  • After that, by using the X2 specification of format, we can format them.
  • The second way is to write a binding value converter using the Binding Value Converter only.

Conclusion

Using string formatting in the different controls makes our task easy and more attractive. We use string formatting to manipulate different objects or any text we want changes in. String formatting helps us to bind the data with controls and display it properly.

Mainly, we use this for defining a unique format for the binding value or blending the value of any control with another new text.

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.

Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

Hire Asp.net developers from iFour Technolab to get your requirements done.

Shankar

Shankar is a tech blogger who occasionally enjoys penning historical fiction. With over a thousand articles written on tech, business, finance, marketing, mobile, social media, cloud storage, software, and general topics, he has been creating material for the past eight years.

Leave a Reply

Your email address will not be published. Required fields are marked *