Xamarin.Forms - Converter In MVVM Using IValueConverter

Introduction

 
 
Xamarin.Forms - Converter In MVVM Using IValueConverter
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
 

Value Converter

 
Use Converter instead of Trigger. Data bindings usually transfer data from a source property to a target property, and in some cases from the target property to the source property. This transfer is straightforward when the source and target properties are of the same type, or when one type can be converted to the other type through an implicit conversion. When that is not the case, a type conversion must take place.
 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

 
Start by creating a new Xamarin.Forms project. You wíll learn more by going through the steps yourself.
 
Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.
 
Xamarin.Forms - Converter In MVVM Using IValueConverter 
 

Create IntToBoolConverer

 
Now, Create an IntToBoolConverer class Derived from IValueConveter
 
I implemented IntToBoolConverter If value !=0 I returns true or else false. Whatever logic you need you can implement it here.
 
IntToBoolConverter.cs
  1. public class IntToBoolConverter : IValueConverter  
  2.     {  
  3.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  4.         {  
  5.             return (int)value != 0;  
  6.         }  
  7.   
  8.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  9.         {  
  10.             return (bool)value ? 1 : 0;  
  11.         }  
  12.   
  13.     }  

Setting up the User Interface

 
Here, Use IntToBoolConverter in your XAML.
 
Add Namespace
  1. xmlns:converters="clr-namespace:XamarinStudy.Common.Converters"   
Add Static Resource
  1. <ContentPage.Resources>    
  2.         <ResourceDictionary>    
  3.             <converters:IntToBoolConverter x:Key="IntToBoolConverter"/>    
  4.         </ResourceDictionary>    
  5.     </ContentPage.Resources>    
MainPage.Xaml
  1. <?xml version="1.0" encoding="utf-8" ?>    
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"    
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"    
  4.              xmlns:d="http://xamarin.com/schemas/2014/forms/design"    
  5.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    
  6.              mc:Ignorable="d"    
  7.              xmlns:converters="clr-namespace:XamarinStudy.Common.Converters"    
  8.              x:Class="XamarinStudy.MainPage" Title="Triggers">    
  9.     
  10.     </ContentPage.Behaviors>    
  11.     <ContentPage.Resources>    
  12.         <ResourceDictionary>    
  13.             <converters:IntToBoolConverter x:Key="IntToBoolConverter"/>    
  14.         </ResourceDictionary>    
  15.     </ContentPage.Resources>    
  16.     <StackLayout Margin="0,30,0,0">    
  17.         <Image Source="banner.png"/>    
  18.         <StackLayout x:Name="PersonList" BindableLayout.ItemsSource="{Binding Persons}"  HorizontalOptions="FillAndExpand">    
  19.         <BindableLayout.ItemTemplate>    
  20.             <DataTemplate>    
  21.                 <StackLayout >    
  22.                     <Label Margin="20,0" Text="{Binding Name}"/>    
  23.                     <Label Margin="20,0" Text="{Binding Age}"/>    
  24.                     <Button Text="Click Me!" IsEnabled="{Binding Count, Converter={StaticResource IntToBoolConverter}}"/>    
  25.                     <BoxView HeightRequest="1" BackgroundColor="Black"/>    
  26.                     <StackLayout.GestureRecognizers>    
  27.                         <TapGestureRecognizer Command="{Binding BindingContext.SelectPersonCommand,Source={x:Reference PersonList}}" CommandParameter="{Binding PersonId}"/>    
  28.                     </StackLayout.GestureRecognizers>    
  29.                 </StackLayout>    
  30.                     
  31.             </DataTemplate>    
  32.         </BindableLayout.ItemTemplate>    
  33.     </StackLayout>    
  34.     </StackLayout>        
  35. </ContentPage>    
Click the "Play" button to try it out.
 
Xamarin.Forms - Converter In MVVM Using IValueConverter
 

ValueToColorConveter

 
In this converter, I used to change color by given values. If value = 0 Red color else Green color.
 
ValueToColorConveter.cs
  1. public class ValueToColorConverter : IValueConverter  
  2.     {  
  3.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  4.         {  
  5.             return (int)value == 0 ? Color.Red : Color.Green;  
  6.         }  
  7.   
  8.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  9.         {  
  10.             return value;  
  11.         }  

  12.     }  
Xamarin.Forms - Converter In MVVM Using IValueConverter
 
Whenever you need to write conditions in XAML use Converter. My suggestion is to use converter instead of Triggers
 
I hope you have understood how to use Converter in MVVM using IValueConverter in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)


Similar Articles