Tuesday, May 10, 2016

How to use IValueConverter in Xamarin

Lets we want to hide an element in XAML by its value, then we can add a IValueConverter in Xamarin PCL library and use it in XAML forms.

1. Create a class file HideIfEmptyValueConverter.cs  and add following code:

 namespace MyApp  
 {  
  class HideIfEmptyValueConverter : IValueConverter  
   {  
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
     {  
       try  
       {  
         if (value != null && (value is string) && (value as string).Length > 0)  
           return true;  
         else if (value != null && (value is IEnumerable<object>) && (value as IEnumerable<object>).Count() > 0)  
           return true;  
         else if (parameter != null && (parameter is string) && (parameter as string).Length > 0)  
           return true;  
         else if (parameter != null && (parameter is IEnumerable<object>) && (parameter as IEnumerable<object>).Count() > 0)  
           return true;  
         else  
           return false;  
       }  
       catch(Exception ex)  
       {  
         return false;  
       }  
     }  
     public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
     {  
       throw new NotImplementedException();  
     }  
   }  
 }   

2. Add Converter as a resource in a XAML page:

  
  <ContentPage.Resources>
      <ResourceDictionary>
        <local:HideIfEmptyValueConverter x:Key="IsVisibleConverter"/>
      </ResourceDictionary>
    </ContentPage.Resources>

3. Use the converter key on any Control:

For example:

                <Label x:Name="Header2"
                       FontSize="Small"
                       Text="{Binding Title2}" 
                       IsVisible="{Binding Title2, Converter={StaticResource IsVisibleConverter}}" />


It should work.