Delpin Susai Raj Thursday, 16 May 2019

Xamarin.Forms - Fast image loading on Android Using GlideX

In this blog post, you will learn how to Fast image loading on Android using GlideX in Xamarin.Forms.


Introduction
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.

GlideX Nuget use to fast image loading on Android.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".
Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

NuGet Packages

Now, add the following NuGet packages.
  • glidex.forms                
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "glidex.forms" and add the resultant package. Remember to install it for each project (.NET Standard, Android, iOS).

Note:

Before you initialize Xamarin.Forms in your MainActivity.cs. you must Initialize FormsMaterial.Init()
FormsMaterial.Init();
view raw MainActivity.cs hosted with ❤ by GitHub
Setting up the User Interface

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:local="clr-namespace:XamarinGlidex"
x:Class="XamarinGlidex.MainPage">
<ScrollView Padding="0">
<Grid x:Name="MainGrid" ColumnSpacing="0" RowSpacing="0">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
</ScrollView>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
Binding Image

MainPage.xaml.cs

using Xamarin.Forms;
namespace XamarinGlidex
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var uri = new Uri("https://thumbor.forbes.com/thumbor/960x0/https%3A%2F%2Fblogs-images.forbes.com%2Fadrianbridgwater%2Ffiles%2F2016%2F02%2F1monkey.jpg");
for (var i = 0; i < 100; i++)
{
MainGrid.RowDefinitions.Add(new RowDefinition { Height = 100 });
for (var j = 0; j < 4; j++)
{
var image = new Image
{
Source = ImageSource.FromUri(uri)
};
Grid.SetRow(image, i);
Grid.SetColumn(image, j);
MainGrid.Children.Add(image);
}
}
}
}
}
Click the "Play" button to try it out.

I hope you have understood how to Fast image loading on Android using GlideX in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Wednesday, 15 May 2019

Xamarin.Forms - Working with Material Visual

In this blog post, you will learn how to use Material design in Xamarin.Forms.


Introduction
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.

Material

Material Design is introduced Xamarin.Forms 3.6
Material Design is an design system created by Google, that prescribes the size, color, spacing, and other aspects of how views and layouts should look and behave.
  • Visual="Material"
  • Visual="Default"
Note:

On Android, the material renderers require a minimum version of 5.0 (API 21) or greater, and a TargetFramework of version 9.0 (API 28). In addition, your platform project requires Android support libraries 28.0.0 or greater, and its theme needs to inherit from a Material Components theme or continue to inherit from an AppCompat theme.

Material renderers are currently included the following Controls:
  1. Button
  2. Entry
  3. Frame
  4. ProgressBar
  5. DatePicker
  6. TimePicker
  7. Picker
  8. ActivityIndicator
  9. Editor
  10. Slider
  11. Stepper
More information about Material
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/visual/material-visual

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".

Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

NuGet Packages

Now, add the following NuGet Packages.
  • Xamarin.Forms.Visual.Material
Add Xamarin.Forms.Visual.Material NuGet

Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Xamarin.Forms.Visual.Material" and add Package. Remember to install it for each project (.NET Standard, Android, iOS).

Note :

Before you initialize Xamarin.Forms in your MainActivity.cs and AppDelegate. you must Initialize FormsMaterial.Init()

FormsMaterial.Init();
view raw MainActivity.cs hosted with ❤ by GitHub
Android Implementation

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
//SetStatusBarColor(global::Android.Graphics.Color.Black);
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
global::Xamarin.Forms.FormsMaterial.Init(this, savedInstanceState);
LoadApplication(new App());
}
view raw MainActivity.cs hosted with ❤ by GitHub
iOS Implementation

AppDelegate.cs

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
global::Xamarin.Forms.FormsMaterial.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
view raw AppDelegate.cs hosted with ❤ by GitHub
Setting up the User Interface

In this step, added material design.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="VisualChallenge.VisualChallengePage"
Shell.NavBarIsVisible="True"
BackgroundColor="White"
Title="Visual Challenge"
>
<ContentPage.ToolbarItems>
<ToolbarItem Order="Primary" Text="Add"></ToolbarItem>
<ToolbarItem Order="Secondary" Priority="0" Text="Update"></ToolbarItem>
</ContentPage.ToolbarItems>
<!-- If you decide to change out the flexlayout leave the scroll view here
Currently there's a bug in shell that will set margins wrong if the content is not in a scrollview
-->
<ScrollView>
<StackLayout Margin="20" >
<Editor Placeholder="EnterSomeThing"></Editor>
<Frame Visual="Material" HeightRequest="150" WidthRequest="150" CornerRadius="5" BorderColor="Red">
<Image Source="monkey.jpg"></Image>
</Frame>
<Frame BorderColor="LightGray">
<Grid Visual="Material">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="200"/>
</Grid.RowDefinitions>
<Frame Grid.Row="0" Visual="Material" Grid.Column="0" BorderColor="LightGray">
<StackLayout >
<Label Text="Monkey"></Label>
<Image Aspect="AspectFit" Source="monkey1.jpg"></Image>
</StackLayout>
</Frame>
<Frame Grid.Row="0" Grid.Column="1" BorderColor="LightGray">
<StackLayout >
<Label Text="Monkey"></Label>
<Image Aspect="AspectFit" Source="monkey2.jpg"></Image>
</StackLayout>
</Frame>
<Frame Grid.Row="1" Grid.Column="0" BorderColor="LightGray">
<StackLayout >
<Label Text="Monkey"></Label>
<Image Aspect="AspectFit" Source="monkey3.jpg"></Image>
</StackLayout>
</Frame>
<Frame Grid.Row="1" Grid.Column="1" BorderColor="LightGray">
<StackLayout >
<Label Text="Monkey"></Label>
<Image Aspect="AspectFit" Source="monkey4.jpg"></Image>
</StackLayout>
</Frame>
</Grid>
</Frame>
</StackLayout>
</ScrollView>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
Click the "Play" button to try it out.

Android Design
iOS Design

I hope you have understood how to use Material design in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback.
Happy Coding :)
Delpin Susai Raj Tuesday, 14 May 2019

Xamarin.Forms - Working with Azure Blob Storage

In this blog post, you will learn how to use Azure Blob Storage in Xamarin.Forms.


Introduction

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.

Azure Blob storage

Azure Blob storage is Microsoft's object storage solution for the cloud. Blob storage is optimized for storing massive amounts of unstructured data.
Store any type of unstructured data—including images, videos, audio, documents and backups. you can write error log also.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)
  • Microsft Azure subscription

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".

Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Create a Storage Account in Azure

http://portal.azure.com

In this step, you must create Storage account service in azure portal.
more about storage account https://docs.microsoft.com/en-us/azure/storage/common/storage-account-overview
After creating storage account, check your access keys and connection strings.

Setting up the User Interface

Go to MainPage.Xaml and write the following code.

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:local="clr-namespace:XamarinBlob"
x:Class="XamarinBlob.MainPage">
<StackLayout>
<!-- Place new controls here -->
<Image Source="banner1.png" HeightRequest="100"/>
<Image WidthRequest="200" HeightRequest="150" x:Name="imgChoosed"></Image>
<Button x:Name="btnPick" Text="Pick" Clicked="BtnPick_Clicked"></Button>
<Button x:Name="btnStore" Text="Upload" Clicked="BtnStore_Clicked"></Button>
<Button x:Name="btnGet" Text="Download" Clicked='BtnGet_Clicked'></Button>
<Button x:Name="btnDelete" Text="Delete" Clicked="BtnDelete_Clicked"></Button>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub


NuGet Packages

Now, add the following NuGet packages.

  1. Xam.Plugin.Media
  2. Microsoft.Azure.Storage.Blob

Add Microsoft.Azure.Storage.Blob NuGet

Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search for "Microsoft.Azure.Storage.Blob" and add the resultant package. Remember to install it for each project (.NET Standard, Android, iOS).

Connect your Storage Account

MediaFile file;
static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJp**********************ocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";
static CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
Pick Files

In this step, i'm going to upload images.

private async void BtnPick_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
try
{
file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (file == null)
return;
imgChoosed.Source = ImageSource.FromStream(() =>
{
var imageStram = file.GetStream();
return imageStram;
});
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}



Upload Files

Now, write the following code to upload files to azure blob storage.

private async void BtnStore_Clicked(object sender, EventArgs e)
{
string filePath = file.Path;
string fileName = Path.GetFileName(filePath);
await cloudBlobContainer.CreateIfNotExistsAsync();
await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
await UploadImage(blockBlob, filePath);
}
private static async Task UploadImage(CloudBlockBlob blob, string filePath)
{
using (var fileStream = File.OpenRead(filePath))
{
await blob.UploadFromStreamAsync(fileStream);
}
}


Download Files

Use following code to download files from azure blob storage.

private async void BtnGet_Clicked(object sender, EventArgs e)
{
string filePath = file.Path;
string fileName = Path.GetFileName(filePath);
var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
await DownloadImage(blockBlob, filePath);
}
private static async Task DownloadImage(CloudBlockBlob blob, string filePath)
{
if (blob.ExistsAsync().Result)
{
await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);
}
}
Delete Files

Use following code to Delete files from azure blog storage.

private async void BtnDelete_Clicked(object sender, EventArgs e)
{
var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
await DeleteImage(blockBlob);
}
private static async Task DeleteImage(CloudBlockBlob blob)
{
if (blob.ExistsAsync().Result)
{
await blob.DeleteAsync();
}
}
Check out Full Code
MainPage.xaml.cs

using Xamarin.Forms;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
using System.IO;
namespace XamarinBlob
{
public partial class MainPage : ContentPage
{
MediaFile file;
static string _storageConnection = "DefaultEndpointsProtocol=https;AccountName=xamarinblob;AccountKey=4bVzkyGnKQrXsJphtzmjnBy0RoyQLgRC8WEvh6ecc9RbWocEMmUXY6df5pXEJPifSDLj6MawSg0aKD2APHWXwQ==;EndpointSuffix=core.windows.net";
static CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
static CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
static CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
public MainPage()
{
InitializeComponent();
}
private async void BtnPick_Clicked(object sender, EventArgs e)
{
await CrossMedia.Current.Initialize();
try
{
file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (file == null)
return;
imgChoosed.Source = ImageSource.FromStream(() =>
{
var imageStram = file.GetStream();
return imageStram;
});
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
private async void BtnStore_Clicked(object sender, EventArgs e)
{
string filePath = file.Path;
string fileName = Path.GetFileName(filePath);
await cloudBlobContainer.CreateIfNotExistsAsync();
await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
});
var blockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
await UploadImage(blockBlob, filePath);
}
private async void BtnGet_Clicked(object sender, EventArgs e)
{
string filePath = file.Path;
string fileName = Path.GetFileName(filePath);
var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
await DownloadImage(blockBlob, filePath);
}
private async void BtnDelete_Clicked(object sender, EventArgs e)
{
var blockBlob = cloudBlobContainer.GetBlockBlobReference("xm.png");
await DeleteImage(blockBlob);
}
private static async Task UploadImage(CloudBlockBlob blob, string filePath)
{
using (var fileStream = File.OpenRead(filePath))
{
await blob.UploadFromStreamAsync(fileStream);
}
}
private static async Task DownloadImage(CloudBlockBlob blob, string filePath)
{
if (blob.ExistsAsync().Result)
{
await blob.DownloadToFileAsync(filePath, FileMode.CreateNew);
}
}
private static async Task DeleteImage(CloudBlockBlob blob)
{
if (blob.ExistsAsync().Result)
{
await blob.DeleteAsync();
}
}
}
}
Click the "Play" button to try it out.


I hope you have understood how to use Azure Blob Storage in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Friday, 10 May 2019

Xamarin.Forms - Working with Triggers

In this blog post, you will learn how to use Triggers in Xamarin.Forms.


Introduction

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.

Triggers

Triggers allow you to express actions declaratively in XAML that change the appearance of controls based on events or property changes.

Triggers Types

  1. Property Trigger executed when a property on a control is set to a particular value.
  2. Data Trigger to trigger based on the properties of another control value.
  3. Event Trigger occurs when an event occurs on the control.
  4. Multi Trigger allows multiple trigger conditions to be set before an action occurs.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".

Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Property Trigger

Property Trigger executed when a property on a control is set to a particular value.

Example

<Entry Placeholder="Enter Something!">
<Entry.Triggers>
<Trigger TargetType="Entry"
Property="IsFocused" Value="True">
<Setter Property="BackgroundColor" Value="Gray" />
</Trigger>
</Entry.Triggers>
</Entry>
view raw Trigger.xaml hosted with ❤ by GitHub
Click the Play button to try it out

Data Trigger

Data Trigger to trigger based on the properties of another control value.

Example

For this example the will be enabled after entering 6 digits.

<Entry x:Name="txtNumber" Placeholder="Enter 6 Digit"></Entry>
<Button Text="Click" IsEnabled="False">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding Source={x:Reference txtNumber},
Path=Text.Length}"
Value="6">
<Setter Property="IsEnabled" Value="True" />
</DataTrigger>
</Button.Triggers>
</Button>
view raw Trigger.xaml hosted with ❤ by GitHub
Click the Play button to try it out

Event Trigger

Event Trigger occurs when an event occurs on the control.

Example

Following example, when change the text in Entry the event will fire.

Trigger Action

public class MonkeyTriggerAction : TriggerAction<Entry>
{
protected override void Invoke(Entry sender)
{
sender.BackgroundColor = Color.Gray;
}
}
Include following namespace

xmlns:local="clr-namespace:XamarinTrigger"
view raw Trigger.xaml hosted with ❤ by GitHub
Implement in xaml

<Entry x:Name="txtNumber" Placeholder="Enter something">
<Entry.Triggers>
<EventTrigger Event="TextChanged">
<local:MonkeyTriggerAction />
</EventTrigger>
</Entry.Triggers>
</Entry>
view raw Trigger.xaml hosted with ❤ by GitHub
Click the "Play" button to try it out.

Multi Trigger
Multi Trigger allows multiple trigger conditions to be set before an action occurs.

Example
The Following example, after entering two field the button will be enabled.

<Entry x:Name="txtNumber1" Placeholder="Enter Number1"></Entry>
<Entry x:Name="txtNumber2" Placeholder="Enter Number2"></Entry>
<Button Text="Click" IsEnabled="False">
<Button.Triggers>
<MultiTrigger TargetType="Button">
<MultiTrigger.Conditions>
<BindingCondition
Binding="{Binding Source={x:Reference txtNumber1},
Path=Text.Length}"
Value="1" />
<BindingCondition
Binding="{Binding Source={x:Reference txtNumber2},
Path=Text.Length}"
Value="1" />
</MultiTrigger.Conditions>
<Setter Property="IsEnabled" Value="True" />
</MultiTrigger>
</Button.Triggers>
</Button>
view raw Trigger.xaml hosted with ❤ by GitHub
Click the "Play" button to try it out.
I hope you have understood how to use Triggers in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Thursday, 9 May 2019

Xamarin.Forms - CollectionView

In this blog post, you will learn how to use CollectionView instead of ListView in Xamarin.Forms.

Introduction

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.

CollectionView

CollectionView is introduce in the Xamarin.Forms 4.0 pre-releases. CollectionView is a view for presenting lists of data using different layout specifications.
It aims to provide a more flexible, and performant alternative to ListView.
  • CollectionView supports single and multiple selection.
  • CollectionView has a flexible layout model, which allows data to be presented vertically or horizontally.
Note:
  • CollectionView is only available on iOS and Android.
More information about Collection View
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/collectionview/

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".

Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Note: 

Before you initialize Xamarin.Forms in your MainActivity.cs and AppDelegate. Add following Flag

Forms.SetFlags("CollectionView_Experimental");
view raw MainActivity.cs hosted with ❤ by GitHub
Android Implementation

MainActivity.cs

protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
view raw MainActivity.cs hosted with ❤ by GitHub
iOS Implementation

AppDelegate.cs

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
view raw AppDelegate.cs hosted with ❤ by GitHub
Setting up the User Interface

Now, Implement the collectionview with data binding.

<?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"
mc:Ignorable="d"
x:Class="CollectionViewChallenge.Views.CollectionViewChallengePage">
<ContentPage.Content>
<StackLayout BackgroundColor="White">
<!-- Use your own layout and functionality here! -->
<CollectionView x:Name="collectionList" Margin="10">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10" Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Frame BackgroundColor="White" Grid.RowSpan="2" CornerRadius="5" Padding="10">
<Image
Source="iphone6.jpeg"
Aspect="AspectFill"
HeightRequest="100"
WidthRequest="100" />
</Frame>
<Label Grid.Column="1"
Text="{Binding Title}"
FontAttributes="Bold" />
<Label Margin="0,20,0,0" Grid.Column="1"
Text="{Binding Description}"
FontAttributes="Bold" />
<Label Grid.Row="1"
Grid.Column="1"
Text="{Binding Price}"
VerticalOptions="End" />
<Frame Grid.Row="0"
Grid.Column="2" BackgroundColor="Pink" Padding="10">
<Label TextColor="White"
Text="{Binding Percentage}"
VerticalOptions="Start" />
</Frame>
<Image Grid.Row="1" Grid.Column="2"
Source="star.png"
HeightRequest="5"
WidthRequest="5" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
CollectionView ItemSource

Now, add ItemSource to CollectionView

using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CollectionViewChallenge.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CollectionViewChallengePage : ContentPage
{
public CollectionViewChallengePage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
List<ListItem> listItems = new List<ListItem>();
ListItem listItem = new ListItem() {Title="iPhone",Description="2GB RAM, 16GB Internal", Price="$500" ,Percentage="50%"};
ListItem listItem1 = new ListItem() { Title = "iPhone", Description = "2GB RAM, 16GB Internal", Price = "$500", Percentage = "50%" };
ListItem listItem2 = new ListItem() { Title = "iPhone", Description = "2GB RAM, 16GB Internal", Price = "$500", Percentage = "50%" };
ListItem listItem3 = new ListItem() { Title = "iPhone", Description = "2GB RAM, 16GB Internal", Price = "$500", Percentage = "50%" };
listItems.Add(listItem);
listItems.Add(listItem1);
listItems.Add(listItem2);
listItems.Add(listItem3);
collectionList.ItemsSource = listItems;
}
}
}
Click the "Play" button to try it out.

I hope you have understood how to use CollectionView instead of ListView in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)
Delpin Susai Raj Wednesday, 8 May 2019

Xamarin.Forms - ListView Context Actions

In this blog post, you will learn how to add a Context Actions in ListView in Xamarin.Forms.

Introduction



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.

Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.

Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.

Now, you need to click "Create a new project".

Now, filter by Project Type: Mobile

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Context Actions

<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="OnEdit" CommandParameter="{Binding Name}" Text="Edit"/>
<MenuItem Clicked="OnDelete" CommandParameter="{Binding Name}" Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
<StackLayout Padding="15,0">
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
view raw gistfile1.txt hosted with ❤ by GitHub
Context Action Events

public void OnEdit(object sender, EventArgs e)
{
var mi = ((MenuItem)sender);
DisplayAlert("Edit", mi.CommandParameter.ToString(), "OK");
}
public void OnDelete(object sender, EventArgs e)
{
var mi = ((MenuItem)sender);
DisplayAlert("Delete", mi.CommandParameter.ToString(), "OK");
}
Setting up the User Interface

Go to MainPage.Xaml and write the following code.

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:local="clr-namespace:XamarinList"
x:Class="XamarinList.MainPage">
<StackLayout>
<Image Margin="20,100,20,0" Source="banner1.png"/>
<ListView x:Name="lstMonkeys">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Clicked="OnEdit" CommandParameter="{Binding Name}" Text="Edit"/>
<MenuItem Clicked="OnDelete" CommandParameter="{Binding Name}" Text="Delete" IsDestructive="True" />
</ViewCell.ContextActions>
<StackLayout Padding="15,0">
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
view raw MainPage.xaml hosted with ❤ by GitHub
MainPage.Xaml.cs

using Xamarin.Forms;
namespace XamarinList
{
public partial class MainPage : ContentPage
{
string[] monkeys = new string[] { "Tamarins", "Capuchins", "Squirrel Monkeys", "Spider Monkeys" };
public MainPage()
{
InitializeComponent();
List<MonkeyList> monkeyLists = new List<MonkeyList>();
foreach (var monkey in monkeys)
{
MonkeyList monkeyList = new MonkeyList() { Name= monkey };
monkeyLists.Add(monkeyList);
}
lstMonkeys.ItemsSource = monkeyLists;
}
public void OnEdit(object sender, EventArgs e)
{
var mi = ((MenuItem)sender);
DisplayAlert("Edit", mi.CommandParameter.ToString(), "OK");
}
public void OnDelete(object sender, EventArgs e)
{
var mi = ((MenuItem)sender);
DisplayAlert("Delete", mi.CommandParameter.ToString(), "OK");
}
}
}
Click the "Play" button to try it out.


I hope you have understood how to add a Context Actions in ListView in Xamarin.Forms..

Thanks for reading. Please share your comments and feedback. Happy Coding :)