Search This Blog

Tuesday 3 December 2019

Xamarin Form Value Converter

Value Converter Example (Enable the button if Entry text length is equal to 10)





MainPage.xaml
<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:local="clr-namespace:TestAppDemo.Converter"
             mc:Ignorable="d"
             x:Class="TestAppDemo.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:NumberValidator x:Key="mobileValidator" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout>
        <Label Text="Enable Button if Text Lenght is equal 10 using Value Converter" FontSize="Large"  TextColor="Black"/>
        <Entry x:Name="txtMobile" Keyboard="Numeric"  Placeholder="Enter Mobile Number"/>
        <Button x:Name="btnSubmit" Text="Submit" IsEnabled="{Binding Source={x:Reference txtMobile},Path=Text.Length,Converter={StaticResource mobileValidator}}" Clicked="Button_Clicked" />
    </StackLayout>
</ContentPage>

MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestAppDemo.ViewModel;
using Xamarin.Forms;
 
namespace TestAppDemo
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void Button_Clicked(object sender, EventArgs e)
        {
            DisplayAlert("OK", "Number is Valid", "OK");
        }
    }
}
 


ValueConverter:
NumberValidator.cs
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Xamarin.Forms;
 
namespace TestAppDemo.Converter
{
    public class NumberValidator : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            try
            {
                if ((int)value == 10)
                {
                    return 1;
                }
                else
                {
                    return 0;
                }
            }
            catch(Exception ex)
            {
                return 0;
            }
        }
 
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}



No comments:

Post a Comment

Popular Posts