Search This Blog

Monday 9 December 2019

Xamarin Form Data Template Selector





DataTemplate Selector: Create the Custom Class that inherits the DataTemplateSelector class.
Then implement the OnSelectTemplate method.


Example: Here in the example I select the template based on isDetail Property of EmployeeModel Class.

CustomTemplateSelector.cs
using System;
using System.Collections.Generic;
using System.Text;
using TestAppDemo.Model;
using Xamarin.Forms;
 
namespace TestAppDemo.Selector
{
    public class CustomTemplateSelector : DataTemplateSelector
    {
        public DataTemplate normalTemplate { get; set; }
        public DataTemplate detailTemplate { get; set; }
        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {
            var obj = (EmployeeModel)item;
            if (obj.isDetail)
            {
                return detailTemplate;
            }
            return normalTemplate;
 
        }
    }
}


EmployeeModel
public  class EmployeeModel
{
      public int Id { get; set; }
      public string Name { get; set; }
      public string Email { get; set; }
      public bool isDetail { get; set; }
      public string Address { get; set; }
}
 


How to Add Template: You can add a template, custom template selector in App.xaml or on a ContentPage using ContentPage.Resources.

<ContentPage.Resources>
        <ResourceDictionary>
                       <!-- DataTemlate with key -->
                      <!-- Custom Template Selector -->
         </ResourceDictionary>
</ContentPage.Resources>

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:selector="clr-namespace:TestAppDemo.Selector"
             mc:Ignorable="d"
             x:Class="TestAppDemo.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary>
            <DataTemplate x:Key="normalDataTemplate">
                <ViewCell >
                    <StackLayout BackgroundColor="LightBlue" >
                        <Label  Text="This is normal Template" />
                        <Label Text="{Binding Name}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
            <DataTemplate x:Key="detailDataTemplate">
                <ViewCell >
                    <StackLayout BackgroundColor="Yellow">
                        <Label Text="This is details template" />
                        <Label Text="{Binding Name}" />
                        <Label Text="{Binding Email}" />
                        <Label Text="{Binding Address}" />
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
 
            <selector:CustomTemplateSelector x:Key="mainTemplate"  normalTemplate="{StaticResource normalDataTemplate}" detailTemplate="{StaticResource  detailDataTemplate}">
            </selector:CustomTemplateSelector>
        </ResourceDictionary>
    </ContentPage.Resources>
    <StackLayout>
        <ListView   ItemTemplate="{StaticResource mainTemplate}" HasUnevenRows="True"  x:Name="lstData">
        </ListView>
    </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.Model;
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();
            ShowData();
        }
        private void ShowData()
        {
            List<EmployeeModel> lst = new List<EmployeeModel>();
            lst.Add(new EmployeeModel()
            {
                Id=0,
                Email="Test@Xamarin.com"
            });
            lst.Add(new EmployeeModel()
            {
                Name = "Test2",
                Email = "Test@Xamarin.com",
                isDetail=true,
                Address="Address1 address 2 address 3"
            });
            lst.Add(new EmployeeModel()
            {
                Name = "Test3",
                Email = "Test@Xamarin.com"
            });
            lst.Add(new EmployeeModel()
            {
                Name = "Test4",
                Email = "Test@Xamarin.com",
                isDetail = true,
                Address = "Address1 address 2 address 3"
            });
 
            lst.Add(new EmployeeModel()
            {
                Name = "Test5",
                Email = "Test@Xamarin.com"
            });
 
            lstData.ItemsSource = lst;
        }
    }
}



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();
        }
    }
}



Sunday 1 December 2019

Xamarin CRUD Operation With EntityFramework (SQLite)








Github URL : https://github.com/mistrypragnesh40/Crud_Demo_UsingSQLIte

Packages Required 




Configure Database
Create the class DatabaseContext that extends the DbContext class.

DatabaseContext.cs
using Crud_Demo_UsingSQLIte.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
 
namespace Crud_Demo_UsingSQLIte
{
    public class DatabaseContext : DbContext
    {
        public DbSet<EmployeeModel> Employees { get; set; }
        public DatabaseContext()
        {
            this.Database.EnsureCreated();
        }
        // overrides the OnConfigure Method 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Employee.db");
            optionsBuilder.UseSqlite($"Filename={dbPath}");
        }
    }
}
 

Models
EmployeeModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
 
namespace Crud_Demo_UsingSQLIte.Models
{
    public class EmployeeModel
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }
}
Services
EmployeeService.cs
using Crud_Demo_UsingSQLIte.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
 
namespace Crud_Demo_UsingSQLIte.Services
{
    public class EmployeeService
    {
        private DatabaseContext getContext()
        {
            return new DatabaseContext();
        }
 
        public async Task<List<EmployeeModel>> GetAllEmployees()
        {
            var _dbContext = getContext();
            var res = await _dbContext.Employees.ToListAsync();
            return res;
        }
 
        public async Task<int> UpdateEmployee(EmployeeModel obj)
        {
            var _dbContext = getContext();
            _dbContext.Employees.Update(obj);
            int c = await _dbContext.SaveChangesAsync();
            return c;
        }
 
        public int InsertEmployee(EmployeeModel obj)
        {
            var _dbContext = getContext();
            _dbContext.Employees.Add(obj);
            int c = _dbContext.SaveChanges();
            return c;
        }
 
        public int DeleteEmployee(EmployeeModel obj)
        {
 
            var _dbContext = getContext();
            _dbContext.Employees.Remove(obj);
            int c = _dbContext.SaveChanges();
            return c;
        }
    }
}
 
Implementation

App.xaml.cs
public App()
{
     InitializeComponent();
     MainPage = new NavigationPage(new ShowEmployeePage());
}
Views
ShowEmployeePage.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"
             Title="Employee Details"
             x:Class="Crud_Demo_UsingSQLIte.Views.ShowEmployeePage">
    <ContentPage.Content>
        <StackLayout Margin="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Button Text="Add New Record" x:Name="btnAddRecord"  HorizontalOptions="Start"  Clicked="btnAddRecord_Clicked" />
 
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Label Text="Name"  FontAttributes="Bold" HorizontalTextAlignment="Start"  Grid.Row="0" Grid.Column="0" />
                <Label Text="Email" FontAttributes="Bold" HorizontalTextAlignment="Start" Grid.Row="0" Grid.Column="1" />
                <Label Text="Address" FontAttributes="Bold" HorizontalTextAlignment="Start" Grid.Row="0" Grid.Column="2" />
            </Grid>
            <ListView x:Name="lstData" HasUnevenRows="True" ItemSelected="lstData_ItemSelected" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell >
                            <Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Label Text="{Binding Name}"   Grid.Row="0" Grid.Column="0" />
                                    <Label Text="{Binding Email}" Grid.Row="0" Grid.Column="1" />
                                    <Label Text="{Binding Address}" Grid.Row="0" Grid.Column="2" />
                                </Grid>
                            </Frame>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

ShowEmployeePage.xaml.cs
using Crud_Demo_UsingSQLIte.Models;
using Crud_Demo_UsingSQLIte.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
 
namespace Crud_Demo_UsingSQLIte.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ShowEmployeePage : ContentPage
    {
        EmployeeService services;
        public ShowEmployeePage()
        {
            InitializeComponent();
            services = new EmployeeService();
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            showEmployee();
        }
        private void showEmployee()
        {
            var res = services.GetAllEmployees().Result;
            lstData.ItemsSource = res;
        }
 
        private void btnAddRecord_Clicked(object sender, EventArgs e)
        {
            this.Navigation.PushAsync(new AddEmployee());
        }
 
        private async void lstData_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem != null)
            {
                EmployeeModel obj = (EmployeeModel)e.SelectedItem;
                string res = await DisplayActionSheet("Operation", "Cancel", null, "Update", "Delete");
 
                switch (res)
                {
                    case "Update":
                        await this.Navigation.PushAsync(new AddEmployee(obj));
                        break;
                    case "Delete":
                        services.DeleteEmployee(obj);
                        showEmployee();
                        break;
                }
                lstData.SelectedItem = null;
            }
        }
    }
}
AddEmployee.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"
             Title="Add/Update Employee"
             x:Class="Crud_Demo_UsingSQLIte.Views.AddEmployee">
    <ContentPage.Content>
        <StackLayout Margin="10" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
            <Entry x:Name="txtName" Placeholder="Enter Name" />
            <Entry x:Name="txtEmail" Placeholder="Enter Email" />
            <Entry x:Name="txtAddress" Placeholder="Enter Address" />
            <Button x:Name="btnSaveUpdate" Text="Save" Clicked="btnSaveUpdate_Clicked" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
AddEmployee.xaml.cs
using Crud_Demo_UsingSQLIte.Models;
using Crud_Demo_UsingSQLIte.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
 
namespace Crud_Demo_UsingSQLIte.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddEmployee : ContentPage
    {
        EmployeeService _services;
        bool _isUpdate;
        int employeeID;
        public AddEmployee()
        {
            InitializeComponent();
            _services = new EmployeeService();
            _isUpdate = false;
        }
        public AddEmployee(EmployeeModel obj)
        {
            InitializeComponent();
            _services = new EmployeeService();
            if (obj != null)
            {
                employeeID = obj.Id;
                txtName.Text = obj.Name;
                txtEmail.Text = obj.Email;
                txtAddress.Text = obj.Address;
                _isUpdate = true;
            }
        }
        private async void btnSaveUpdate_Clicked(object sender, EventArgs e)
        {
            EmployeeModel obj = new EmployeeModel();
            obj.Name = txtName.Text;
            obj.Email = txtEmail.Text;
            obj.Address = txtAddress.Text;
            if (_isUpdate)
            {
                obj.Id = employeeID;
                await _services.UpdateEmployee(obj);
            }
            else
            {
                _services.InsertEmployee(obj);
            }
            await this.Navigation.PopAsync();
        }
    }
}

Popular Posts