Introduction In this post, we are going see the featured effects available in Xamarin Community Toolkit a...

Xamarin Community Toolkit - Effects Xamarin Community Toolkit -  Effects

A blog about android developement

Introduction

In this post, we are going see the featured effects available in Xamarin Community Toolkit and how to use them. This post is a part of Xamarin Community Toolkit - Tutorial Series and visit the post for know about the Xamarin Community Toolkit. The Xamarin Community Toolkit is a collection of reusable elements for mobile development with Xamarin.Forms, including animations, behaviors, converters, effects, and helpers. It simplifies and demonstrates common developer tasks when building iOS, Android, macOS, WPF and Universal Windows Platform (UWP) apps using Xamarin.Forms. 

Coding Part

Steps

  1. Step 1: Creating new Xamarin.Forms Projects.
  2. Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project.
  3. Step 3: Implementation of Effects using Xamarin Community Toolikit.

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New Project à Select Xamarin Cross Platform App and Click OK.

Note: Xamarin.Forms version should be greater than 5.0.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project

    In this step, we will see how to setup the plugin.

  • Open the Nuget Manager in the Visual Studio Solution by right click the solution and select “Manage Nuget Packages”.
  • Then select “Xamarin Community Toolkit” and check all the projects in the solution, install the plugin

Step 3: Implementation of Effects using Xamarin Community Toolikit.

In this step, we will see how to implement the featured effects offered in Xamarin Community Toolkit. Here, we have expalined the implementation of Safe Area Effect, Shadow Effect, Life Cycle Effect and StatusBar Effect.

  • Open your XAML design file and add the following namespace to utilise the views in the screen.
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"

SafeAreaEffect

  • The SafeAreaEffect is an effect that can be added to any element through an attached property to indicate whether or not that element should take current safe areas into account.
  • This is an area of the screen that is safe for all devices that use iOS 11 and greater.
  • Specifically, it will help to make sure that content isn't clipped by rounded device corners, the home indicator, or the sensor housing on an iPhone X. The effect only targets iOS, meaning that on other platforms it does not do anything.
  • Properties:
      SafeArea - Indicates which safe areas should be taken into account for this element
<StackLayout xct:SafeAreaEffect.SafeArea="True" BackgroundColor="White"> </StackLayout>

Before Applying the Effect

After Applying the Effect

ShadowEffect

  • It is used to have shadow effect for Xamarin Forms Views and we have five properties that need to be understood to using this effect.
  • Properties:
    1. Color: It's the color that the shadow will have.
    2. Opacity: With this property, you can control the opacity you want in the shadow.
    3. Radius: It’s responsible for handling the blurring in the shadow.
    4. OffsetX/OffsetY: It allows us to define the displacement that the shadow will have, therefore OffsetX is responsible for specifying the distance of the horizontal displacement, while OffsetY of the vertical displacement.
  • In this example, I have updated the shadow effect for the Image Control like in the following code block
    <Image
    	x:Name="img"
    	HeightRequest="150"
    	Margin="10"
    	xct:ShadowEffect.Color="Green" 
    	xct:ShadowEffect.OffsetY="15"
    	Source="https://shorturl.at/qsvJ1">
    </Image>

Lifecycle Effect

  • The LifecycleEffect allows you to determine when a VisualElement has its renderer allocated by the platform. It can be identified by using the LifeCycleEffect event handlers.
<Image
	x:Name="img"
	HeightRequest="150"
	Margin="10"
	Source="https://shorturl.at/qsvJ1">
	<Image.Effects>
		<xct:LifecycleEffect Loaded="LifeCycleEffect_Loaded" Unloaded="LifeCycleEffect_Unloaded" />
	</Image.Effects>
</Image>
private void LifeCycleEffect_Loaded(object sender, EventArgs e)
{
	Console.WriteLine("Image loaded...");
}

private void LifeCycleEffect_Unloaded(object sender, EventArgs e)
{
	Console.WriteLine("Image Unloaded...");
}

Statusbar Effect

  • This effect is used to control the status bar color in the Xamarin Forms Application during the compile time or runtime or like button clicks. It is a single line code to be useful to control.
  • In this example, we will create color resource in the App.xaml file like below. It will be updated later dynamically.
    <Color x:Key="StatusBarColor">Firebrick</Color>
  • Then add the following line in the root element of your XAML page as a DynamicResource
    xct:StatusBarEffect.Color="{DynamicResource StatusBarColor}"
  • Then add the 3 buttons like in the sample screen and update your dynamic resource color on button click like below.
    private void ButtonClicked(object sender, EventArgs e)
    {
    	Application.Current.Resources["StatusBarColor"] = ((Button)sender).TextColor;            
    }

Full Code:

<?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:xct="http://xamarin.com/schemas/2020/toolkit"
             x:Class="XamarinCommunityToolkit.EffectsSamplePage"
             xct:StatusBarEffect.Color="{DynamicResource StatusBarColor}">
    <ContentPage.Content>
        <StackLayout xct:SafeAreaEffect.SafeArea="True"
                     BackgroundColor="White">

            <Frame BackgroundColor="#2196F3" 
                   Padding="24" 
                   CornerRadius="0">
                <Label Text="Xamarin Forms Effects using XCT" 
                       HorizontalTextAlignment="Center" 
                       TextColor="White" 
                       FontSize="36"/>
            </Frame>
            
            <Image
                x:Name="img"
                HeightRequest="150"
                Margin="10"
                xct:ShadowEffect.Color="Green" 
                xct:ShadowEffect.OffsetY="15"
                Source="https://shorturl.at/qsvJ1">
                <Image.Effects>
                    <xct:LifecycleEffect Loaded="LifeCycleEffect_Loaded" Unloaded="LifeCycleEffect_Unloaded" />
                </Image.Effects>
            </Image>
            <Grid Padding="10">
                <Button Clicked="ButtonClicked" Text="Red" TextColor="Red" BorderColor="Red" BorderWidth="2" Grid.Column="0"/>
                <Button Clicked="ButtonClicked" Text="Green" TextColor="Green" BorderColor="Green" BorderWidth="2" Grid.Column="1"/>
                <Button Clicked="ButtonClicked" Text="Blue" TextColor="Blue" BorderColor="Blue" BorderWidth="2" Grid.Column="2"/>
            </Grid>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
The XCT offering other type effects as well and please visit the below link for more samples. https://github.com/xamarin/XamarinCommunityToolkit/tree/main/samples/XCT.Sample/Pages/Effects

Download Code:

You can download the code from GitHub. If you have doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.


Introduction In this post, we are going see the "How to create Master Details Page using Xamarin Community To...

Master Details Page using Xamarin Community Toolkit Master Details Page using Xamarin Community Toolkit

A blog about android developement

Introduction

In this post, we are going see the "How to create Master Details Page using Xamarin Community Toolkit". To know more about Xamarin Community Toolkit, check the previous posts.

Coding Part

Steps

  1. Step 1: Creating new Xamarin.Forms Projects
  2. Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project
  3. Step 3: Implementation of Master Details Page using Xamarin Community Toolkit

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New Project à Select Xamarin Cross Platform App and Click OK.

Note: Xamarin.Forms version should be greater than 5.0.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project

    In this step, we will see how to setup the plugin.

  • Open the Nuget Manager in the Visual Studio Solution by right click the solution and select “Manage Nuget Packages”.
  • Then select “Xamarin Community Toolkit” and check all the projects in the solution, install the plugin

Step 3: Implementation of Master Details Page using Xamarin Community Toolkit.

    In this step, we will see how to implement the Implementation of Master Details Page using Xamarin Community Toolkit in XAML. We have expalined the steps below.

  • Open your XAML design file and add the following namespace to utilise the views in the screen.
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
  • SideMenuView
    1. Basically, SideMenuView can be added as a child to any layout (e.g. you can put SideMenuView inside StackLayout or even make every item view in CollectionView be SideMenuView as well) or into ContentPage as the root view.
    2. Here, three views inside the SideMenuView. These views represent the Main View, the Left Menu, the Right Menu. This can be determined by using "SideMenuView.Position" property.
    3. SideMenuView.MenuWidthPercentage attached property for determining side menu's size.
    <xct:SideMenuView x:Name="SideMenu">
    	<!--MainView-->
    	<AbsoluteLayout BackgroundColor="White">
    
    		<StackLayout AbsoluteLayout.LayoutFlags="All"
    			AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
    				   VerticalOptions="Center"
    				   HorizontalOptions="Center">
    
    			<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
    				<Label Text="Master Detail Page using XCT" 
    					   HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
    			</Frame>
    
    			<Label Text="<-- Swipe Left or Right -->"
    				   TextColor="Black"
    				   VerticalOptions="Center"
    				   HorizontalOptions="Center"
    				   FontSize="20"/>
    
    		</StackLayout>
    
    		<StackLayout Orientation="Horizontal"
    					 Padding="15, 10"
    					 AbsoluteLayout.LayoutFlags="WidthProportional"
    					 AbsoluteLayout.LayoutBounds="0, 0, 1, -1">
    			<Button Text="|||"
    					TextColor="White"
    					BackgroundColor="#2196F3"
    					WidthRequest="40"
    					FontSize="20"
    					VerticalOptions="Center"
    					Clicked="OnLeftButtonClicked"/>
    			<Button Text="|||"
    					BackgroundColor="#2196F3"
    					TextColor="White"
    					WidthRequest="40"
    					VerticalOptions="Center"
    					FontSize="20"
    					HorizontalOptions="EndAndExpand"
    					Clicked="OnRightButtonClicked" />
    		</StackLayout>
    	</AbsoluteLayout>
    
    	<!--LeftMenu-->
    	<ScrollView xct:SideMenuView.Position="LeftMenu"
    				xct:SideMenuView.MenuWidthPercentage="0.5"
    				BackgroundColor="Orange">
    		<StackLayout HeightRequest="2000">
    			<Button Text="TO RIGHT" FontSize="25" Clicked="OnRightButtonClicked" />
    		</StackLayout>
    	</ScrollView>
    
    	<!--RightMenu-->
    	<ScrollView xct:SideMenuView.Position="RightMenu"
    				xct:SideMenuView.MenuWidthPercentage="0.35"
    				BackgroundColor="Gold">
    		<StackLayout HeightRequest="2000">
    			<Button Text="TO LEFT" FontSize="25" Clicked="OnLeftButtonClicked" />
    		</StackLayout>
    	</ScrollView>
    
    </xct:SideMenuView>
  • Opening the side menu from right or left can be controlled by the State property of the SideMenuView.
    SideMenu.State = SideMenuState.LeftMenuShown; (or SideMenuState.RightMenuShown;)

Demo:

Download Code:

You can download the code from GitHub. If you have doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.


Introduction In this post, we are going see the featured views available in Xamarin Community Toolkit and how to...

Xamarin Community Toolkit - Featured Views Xamarin Community Toolkit -  Featured Views

A blog about android developement

Introduction

In this post, we are going see the featured views available in Xamarin Community Toolkit and how to use them. This post is a part of Xamarin Community Toolkit - Tutorial Series and visit the post for know about the Xamarin Community Toolkit. The Xamarin Community Toolkit is a collection of reusable elements for mobile development with Xamarin.Forms, including animations, behaviors, converters, effects, and helpers. It simplifies and demonstrates common developer tasks when building iOS, Android, macOS, WPF and Universal Windows Platform (UWP) apps using Xamarin.Forms. 

Coding Part

Steps

  1. Step 1: Creating new Xamarin.Forms Projects.
  2. Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project.
  3. Step 3: Implementation of Xamarin Community featured views.

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New Project à Select Xamarin Cross Platform App and Click OK.

Note: Xamarin.Forms version should be greater than 5.0.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Setting up the Xamarin Community Toolkit in Xamarin.Forms .Net Standard Project

    In this step, we will see how to setup the plugin.

  • Open the Nuget Manager in the Visual Studio Solution by right click the solution and select “Manage Nuget Packages”.
  • Then select “Xamarin Community Toolkit” and check all the projects in the solution, install the plugin

Step 3: Implementation of Xamarin Community featured views.

    In this step, we will see how to implement the XCT featured views in XAML. We have expalined the usage with Avatar View and Expander View

  • Open your XAML design file and add the following namespace to utilise the views in the screen.
    xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
  • AvatarView
    The AvatarView control allows the user to display an avatar or the user's initials if no avatar is available. By binding the Source property the user can assign an image to the AvatarView. Simultaneously binding the Text property will allow the user to also set the initials to be shown if no valid image is provided. It can used like the below code part.
    <xct:AvatarView Text="M" Source="https://www.c-sharpcorner.com/UploadFile/AuthorImage/553bbc20200726035629.jpg" HorizontalOptions="Center"/>
  • ExpanderView
    The Xamarin.CommunityToolkit Expander control provides an expandable container to host any content. The control has a header and content, and the content is shown or hidden by tapping the Expander header. When only the Expander header is shown, the Expander is collapsed. When the Expander content is visible the Expander is expanded. To know more about this control, click here.
    <xct:Expander >
        <xct:Expander.Header>
            <Grid Padding="10">
                <Label Text="Xamarin Community Toolkit - Views"
               FontSize="16" />
                <Image Source="expand.png"
                       WidthRequest="16"
                       HorizontalOptions="End"
                       VerticalOptions="Center">
                    <Image.Triggers>
                        <DataTrigger TargetType="Image"
                             Binding="{Binding Source={RelativeSource AncestorType={x:Type xct:Expander}}, Path=IsExpanded}"
                             Value="True">
                            <Setter Property="Rotation"
                            Value="180" />
                        </DataTrigger>
                    </Image.Triggers>
                </Image>
            </Grid>
        </xct:Expander.Header>
        <xct:Expander.ContentTemplate>
            <DataTemplate>
                <Grid Padding="10"
                      HorizontalOptions="FillAndExpand"
                      VerticalOptions="FillAndExpand">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Image Source="https://tinyurl.com/4pp4mn7e"
                           HeightRequest="45"
                           Aspect="Fill"/>
                    <Label Grid.Column="1"
                           VerticalOptions="FillAndExpand"
                           Text="The Xamarin Community Toolkit is a collection of reusable elements for mobile development with Xamarin.Forms, including animations, behaviors, converters, effects, and helpers. It simplifies and demonstrates common developer tasks when building iOS, Android, macOS, WPF and Universal Windows Platform (UWP) apps using Xamarin.Forms."
                   FontAttributes="Italic" />
                </Grid>
            </DataTemplate>
        </xct:Expander.ContentTemplate>
    </xct:Expander>
  • UniformGrid
    The UniformGrid is like the Grid, with the possibility of multiple rows and columns, but with one important difference: all rows and columns have the same size. That size is determined by the largest width and height of all the child elements. The child element with the largest width does not necessarily have to be the child element with the largest height. Use the UniformGrid when you need the Grid behavior without the need to specify different sizes for the rows and columns.
    <xct:UniformGrid>
        <BoxView Color="Red" />
        <BoxView Color="Yellow" />
        <BoxView Color="Orange" />
        <BoxView Color="Purple" />
        <BoxView Color="Blue" />
        <BoxView Color="Green" />
        <BoxView Color="LightGreen" />
        <BoxView Color="Gray" />
        <BoxView Color="Pink" />
    </xct:UniformGrid>
  • Here, I have listed the few views featured in the XCT plugin and the below controls are available with XCT
    1. AvatarView
    2. BadgeView
    3. CameraView
    4. DockLayout
    5. Expander
    6. LazyView
    7. MediaElement
    8. Popup
    9. RangeSlider
    10. Shield
    11. StateLayout
    12. TabView
    13. UniformGrid

Full Code:

<?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:xct="http://xamarin.com/schemas/2020/toolkit"
             x:Class="XamarinCommunityToolkit.MainPage">

    <StackLayout Spacing="0">
        <Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
            <Label Text="Xamarin Community Toolkit Tutorial Series!" HorizontalTextAlignment="Center" TextColor="White" FontSize="36"/>
        </Frame>

        <Label Text="Avatar View"
               FontSize="16"
               Padding="10"
               FontAttributes="Bold"/>

        <xct:AvatarView Text="M" Source="https://www.c-sharpcorner.com/UploadFile/AuthorImage/553bbc20200726035629.jpg" 
                        HorizontalOptions="Center"/>
        <Label Text="Expander View"
               FontSize="16"
               Padding="10"
               FontAttributes="Bold"/>
        
        <xct:Expander >
            <xct:Expander.Header>
                <Grid Padding="10">
                    <Label Text="Xamarin Community Toolkit - Views"
                   FontSize="16" />
                    <Image Source="expand.png"
                           WidthRequest="16"
                           HorizontalOptions="End"
                           VerticalOptions="Center">
                        <Image.Triggers>
                            <DataTrigger TargetType="Image"
                                 Binding="{Binding Source={RelativeSource AncestorType={x:Type xct:Expander}}, Path=IsExpanded}"
                                 Value="True">
                                <Setter Property="Rotation"
                                Value="180" />
                            </DataTrigger>
                        </Image.Triggers>
                    </Image>
                </Grid>
            </xct:Expander.Header>
            <xct:Expander.ContentTemplate>
                <DataTemplate>
                    <Grid Padding="10"
                          HorizontalOptions="FillAndExpand"
                          VerticalOptions="FillAndExpand">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
                        <Image Source="https://tinyurl.com/4pp4mn7e"
                               HeightRequest="45"
                               Aspect="Fill"/>
                        <Label Grid.Column="1"
                               VerticalOptions="FillAndExpand"
                               Text="The Xamarin Community Toolkit is a collection of reusable elements for mobile development with Xamarin.Forms, including animations, behaviors, converters, effects, and helpers. It simplifies and demonstrates common developer tasks when building iOS, Android, macOS, WPF and Universal Windows Platform (UWP) apps using Xamarin.Forms."
                       FontAttributes="Italic" />
                    </Grid>
                </DataTemplate>
            </xct:Expander.ContentTemplate>
        </xct:Expander>
        
        <Label Text="Uniform Grid"
               FontSize="16"
               Padding="10"
               FontAttributes="Bold"/>
        
        <xct:UniformGrid>
            <BoxView Color="Red" />
            <BoxView Color="Yellow" />
            <BoxView Color="Orange" />
            <BoxView Color="Purple" />
            <BoxView Color="Blue" />
            <BoxView Color="Green" />
            <BoxView Color="LightGreen" />
            <BoxView Color="Gray" />
            <BoxView Color="Pink" />
        </xct:UniformGrid>
    </StackLayout>

</ContentPage>

Demo:

Download Code:

You can download the code from GitHub. If you have doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.


From this post, we are going to see about Xamarin Community Toolkit, followed by the features of this Xamarin Community Toolkit a...

Xamarin Community Toolkit - Tutorial Series Xamarin Community Toolkit - Tutorial Series

A blog about android developement

img

From this post, we are going to see about Xamarin Community Toolkit, followed by the features of this Xamarin Community Toolkit as a series of tutorials.

Xamarin Community Toolkit

The Xamarin Community Toolkit is a collection of reusable elements for mobile development with Xamarin.Forms, including animations, behaviors, converters, effects, and helpers. It simplifies and demonstrates common developer tasks when building iOS, Android, macOS, WPF and Universal Windows Platform (UWP) apps using Xamarin.Forms. 

The Xamarin Community Toolkit is available as a Visual Studio NuGet package for new or existing Xamarin.Forms projects. This includes the beloved C# UI Extensions, MediaElement, and Expander controls. There is much more to the toolkit though as the community has been contributing tons of great new controls and helpers. You can also preview the capabilities of the toolkit by running the sample app available in the Xamarin Community Toolkit repo.

Features of Xamarin Community Toolkit

This toolkit’s offers many of those behaviors, converters, and effects that you keep copying from one project to another and aggregate all of these into a single package so it will become your one-stop library that has it all. The Toolkit will also be a place where you can find brand new controls. Some of them come from PRs to Xamarin.Forms that couldn’t be included in the main package, some our controls maintainers donating their controls, and some are just brand-new things!

  1. Behaviors
    • Animations
    • Validators
    • EventloCommand
    • ImpliedOrderGrid
    • Masked (input)
    • UserStoppedTyping
  2. Converters
    • ByteArrayTolmageSource
    • ItemSelectedEventArgs
    • MultiConverterParameter
    • NotEqual
    • TextCase
  3. Effects
    • SafeArea
  4. Extensions
    • ImageResource
    • Translate
    • ValueConverter
  5. Helpers
    • Localization
    • Subscription
    • WeakEvent
  6. ObjectModel
    • AsyncCommand
    • ObservableRangeCollection
  7. Views
    • CameraView
    • Expander
    • SideMenuView
    • AvatarView
    • RangeSlider

Setup Xamarin Community Toolkit

  • The toolkit is available as a NuGet package that can be added to any existing or new project using Visual Studio. Open an existing project, or create a new project using the Blank Forms App template.
  • In the Solution Explorer panel, right click on your project name and select Manage NuGet Packages. Search for Xamarin.CommunityToolkit, and choose the desired NuGet Package from the list.
    img
  • To add the namespace to the toolkit, In your C# page, add
     using Xamarin.CommunityToolkit;
    In your XAML page, add the namespace attribute:
     xmlns:xct="http://xamarin.com/schemas/2020/toolkit"

We will see the upcoming tutorials on Xamarin Community Toolkit

Introduction In this article, we will learn how to embed and use the barcode scanner inside the screen/page using the Xamarin.Forms Fram...

Embedding QR Code Scanner in Xamarin.Forms Embedding QR Code Scanner in Xamarin.Forms

A blog about android developement

Introduction

In this article, we will learn how to embed and use the barcode scanner inside the screen/page using the Xamarin.Forms Framework. For achieving this, we are going to use “ZXing.Net.Mobile” plugin.

Dropdown in Xamarin.Forms

ZXing.Net.Mobile plugin is a useful plugin to facilitate scanning barcodes as effortless and painless as possible in our own applications works Xamarin.iOS, Xamarin.Android, Tizen, and UWP.

Library Link: https://github.com/Redth/ZXing.Net.Mobile

Without much introduction, we will skip into the coding part of this article.

Coding Part

Steps

Step 1: Creating new Xamarin.Forms Projects.

Step 2: Setting up the scanner in Xamarin.Forms .Net Standard Project

Step 3: Implementation of QR Code Scanner inside the screen/page

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New à Project à Select Xamarin Cross Platform App and Click OK.

Note: Xamarin.Forms version should be greater than 4.5.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Setting up the scanner in Xamarin.Forms .Net Standard Project

In this step, we will see how to setup the plugin.

  • Open the Nuget Manager in the Visual Studio Solution by right click the solution and select “Manage Nuget Packages”.
  • Then “ZXing.Net.Mobile” and check all the projects in the solution, install the plugin
  • After the installation, we need to do some additional setup in the platform wise projects.
  • In Android, update the below code blocks in the MainActivity to initialize the plugin.
// In OnCreate method
Xamarin.Essentials.Platform.Init(Application);
ZXing.Net.Mobile.Forms.Android.Platform.Init();

// In Activity to handle the camera permission from the plugin it self.

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}

Step 3: Implementation of QR Code Scanner inside the screen/page

In this step, we will see how to use the view in Xamarin.Forms.

  • Open your designer file and in my case MainPage.xaml and add the ZxingSannerView as shown below.
    <zxing:ZXingScannerView x:Name="zxing"
                            VerticalOptions="FillAndExpand"/>
  • Add Label below the ZxingSannerView to see the results when the bar/QR code scanned.
  • Then add the below event to know the successful scan from the control.
    zxing.OnScanResult += (result) =>
          Device.BeginInvokeOnMainThread(() =>
          {
                lblResult.Text = result.Text;
          });

Full Code implementation of ZXing Scanner View in MainPage

Here, we will see the full code for Main Page.

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        zxing.OnScanResult += (result) =>
            Device.BeginInvokeOnMainThread(() =>
            {
                lblResult.Text = result.Text;
            });
    }


    protected override void OnAppearing()
    {
        base.OnAppearing();
        zxing.IsScanning = true;
    }

    protected override void OnDisappearing()
    {
        zxing.IsScanning = false;
        base.OnDisappearing();
    }
}

Demo

The following screens shows the output this tutorial and it is awesome to have this dropdown in Xamarin.Forms

Download Code

You can download the code from GitHub. If you have doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.

Introduction In this article, we will learn how to create Dropdown in Xamarin.Forms (Xamarin.iOS). As we learned in the previous article...

Dropdown control in Xamarin.Forms – Part Two Dropdown control in Xamarin.Forms – Part Two

A blog about android developement

banner_dropdown_part2

Introduction

In this article, we will learn how to create Dropdown in Xamarin.Forms (Xamarin.iOS). As we learned in the previous article about by default, Android Platform has dropdown called as “Spinner”, but iOS Platform has no dropdown like Android Spinner and how to achieve the dropdown in Xamarin.Forms for Android Platform using Custom renderer approach. In this article, we are going to create a custom renderer to achieve the dropdown for iOS platform in Xamarin.Forms.

Dropdown in Xamarin.Forms

Please refer the previous article to know, how to achieve the dropdown in Android Platform. I have done changes commonly for Android and iOS in this article.

We will go for custom renderer approach to have a new control to wrap a Platform specific control. I am going to use “FPTInformationSystem Dropdown” and refer the below link to know more details for this control.

Library Link: https://github.com/FPTInformationSystem/Dropdown-Xamarin-iOS

Without much introduction, we will skip into the coding part of this article.

Coding Part

Steps

Here, I will explain the steps to create Dropdown in Xamarin.Forms.

Step 1: Creating new Xamarin.Forms Projects.

Step 2: Creating a Dropdown view in Xamarin.Forms .NetStandard Project

Step 3: Wrapping FPT dropdown for Dropdown control in iOS Project.

Step 4: Implementation of Dropdown & It’s Demo for iOS Platform.

Step 1: Creating new Xamarin.Forms Projects

Create New Project by Selecting New à Project à Select Xamarin Cross Platform App and Click OK.

Note: Xamarin.Forms version should be greater than 4.5.

Then Select Android and iOS Platforms as shown below with Code Sharing Strategy as PCL or .Net Standard and Click OK.

Step 2: Creating a Dropdown view in Xamarin.Forms .NetStandard Project

In this step, we will see how to create a dropdown view with required properties.

  • Create a class named as “Dropdown” and inherit the Dropdown with “Label”. That is Dropdown is child of View.
    public class Dropdown :  Label
    {
      //...
    }
  • Then we will create a required bindable properties. First we will see, what are all the properties & events required for dropdown.
    1. ItemsSource – To assign the list of data to be populated in the dropdown.
    2. SelectedIndex – To identify the index of selected values from the ItemsSource.
    3. ItemSelected – Event for performing action when the item selected in the dropdown.
  • Create a bindable property for the ItemsSource as shown in below.
    public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
          propertyName: nameof(ItemsSource),
          returnType: typeof(List<string>),
          declaringType: typeof(List<string>),
          defaultValue: null);
    
    public List<string> ItemsSource
    {
          get { return (List<string>)GetValue(ItemsSourceProperty); }
          set { SetValue(ItemsSourceProperty, value); }
    }

Step 3: Wrapping FPT dropdown for Dropdown control in iOS Project.

In this step, we will see “How to wrap the iOS Spinner Control for Dropdown View”.

  • We need to download the DLL of FPT dropdown from the below GitHub link and include as a reference for the iOS project. Library Download Link
  • Create a class file named as “DropdownRenderer” in your iOS client project and add View Renderer as shown in below. I am using Label renderer for displaying the dropdown when the control tapped.
    public class DropdownRenderer :  LabelRenderer
    {
          XFDropdown xfDropdown = null;
          XIDropdown dropDown = null;
          public DropdownRenderer()
          {
    
          }    
          // ...
    }
  • Then Override the methods “OnElementChanged” and “OnElementPropertyChanged”. OnElementChanged method is triggered on element/control initiation. OnElementPropertyChanged method is called when the element property changes.
  • Set Control properties to LabelRenderer in OnElementChanged override method as shown in below.
  • We need to follow the below for initiating the FPT dropdown and open when the label tapped.
    if (Control != null)
    {
        dropDown = new XIDropdown();
        xfDropdown = (XFDropdown)e.NewElement;
        dropDown.AnchorView = new WeakReference<UIView>(Control);
        nfloat y = dropDown.Bounds.Height;
        if (y == 0)
            y += 40;
        dropDown.TopOffset = new CoreGraphics.CGPoint(0, -y);
        dropDown.BottomOffset = new CoreGraphics.CGPoint(0, y);
    
        //...
    
        UITapGestureRecognizer labelTap = new UITapGestureRecognizer(() =>
        {
            dropDown.Show();
        });
    
        if (xfDropdown.SelectedIndex > -1)
            Control.Text = xfDropdown.ItemsSource[xfDropdown.SelectedIndex];
        Control.UserInteractionEnabled = true;
        Control.AddGestureRecognizer(labelTap);
    }
  • Set Items Source from Xamarin.Forms Dropdown to FPT dropdown control as shown in below.
    string[] data = xfDropdown.ItemsSource.ToArray();
    dropDown.DataSource = data;
  • Set default selection of item from selected index as shown in below.
    if(xfDropdown.SelectedIndex != -1)
    {
          dropDown.SelectRow(xfDropdown.SelectedIndex);
    }
  • Create an item selected event for FPT dropdown and invoke the dropdown event created as shown below
    // ...
    
    dropDown.SelectionAction = (nint idx, string item) =>
    {
          if (xfDropdown.SelectedIndex == idx)
          {
                dropDown.Dispose();
                return;
          }
    
          xfDropdown.SelectedIndex = Convert.ToInt32(idx);
          Control.Text = item;
          xfDropdown.OnItemSelected(xfDropdown.SelectedIndex);
    };
  • In the same way, we will assign ItemsSource & SelectedIndex to FPT dropdown when the property changes using OnElementPropertyChanged as shown below.
    protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
          base.OnElementPropertyChanged(sender, e);
          dropDown.Width = (nfloat)Element.Width;
          if (e.PropertyName == XFDropdown.SelectedIndexProperty.PropertyName)
          {
                if (xfDropdown.SelectedIndex > -1)
                      Control.Text = xfDropdown.ItemsSource[xfDropdown.SelectedIndex];
                dropDown.SelectRow(xfDropdown.SelectedIndex);
          }
    
          if (e.PropertyName == XFDropdown.ItemsSourceProperty.PropertyName)
          {
                string[] data = xfDropdown.ItemsSource.ToArray();
                dropDown.DataSource = data;
          }
    }
  • Add Export Renderer above the namespace to link dropdown view in .NetStandard project to iOS Client Project. This is very important step for any custom renderer approach.
    [assembly: ExportRenderer(typeof(Dropdown), typeof(DropdownRenderer))]
    namespace XF.Ctrls.iOS

Full Code of Dropdown Renderer

Here, we will see the full code for Dropdown Renderer.

[assembly: ExportRenderer(typeof(XFDropdown), typeof(DropdownRenderer))]
namespace XF.Ctrls.iOS
{
    public class DropdownRenderer : LabelRenderer
    {

        XFDropdown xfDropdown = null;
        XIDropdown dropDown = null;

        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            if (Control != null)
            {
                dropDown = new XIDropdown();
                xfDropdown = (XFDropdown)e.NewElement;
                dropDown.AnchorView = new WeakReference<UIView>(Control);
                nfloat y = dropDown.Bounds.Height;
                if (y == 0)
                    y += 40;

                dropDown.TopOffset = new CoreGraphics.CGPoint(0, -y);
                dropDown.BottomOffset = new CoreGraphics.CGPoint(0, y);
                string[] data = xfDropdown.ItemsSource.ToArray();
                dropDown.DataSource = data;
                Control.Text = data[0];
                dropDown.SelectionAction = (nint idx, string item) =>
                {
                    if (xfDropdown.SelectedIndex == idx)
                    {
                        dropDown.Dispose();
                        return;
                    }
                    xfDropdown.SelectedIndex = Convert.ToInt32(idx);
                    Control.Text = item;
                    xfDropdown.OnItemSelected(xfDropdown.SelectedIndex);
                };

                UITapGestureRecognizer labelTap = new UITapGestureRecognizer(() =>
                {
                    dropDown.Show();
                });

                if (xfDropdown.SelectedIndex > -1)
                    Control.Text = xfDropdown.ItemsSource[xfDropdown.SelectedIndex];
                Control.UserInteractionEnabled = true;
                Control.AddGestureRecognizer(labelTap);
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            dropDown.Width = (nfloat)Element.Width;
            if (e.PropertyName == XFDropdown.SelectedIndexProperty.PropertyName)
            {
                if (xfDropdown.SelectedIndex > -1)
                    Control.Text = xfDropdown.ItemsSource[xfDropdown.SelectedIndex];
                dropDown.SelectRow(xfDropdown.SelectedIndex);
            }
            if (e.PropertyName == XFDropdown.ItemsSourceProperty.PropertyName)
            {
                string[] data = xfDropdown.ItemsSource.ToArray();
                dropDown.DataSource = data;
            }
        }
    }
}

Step 4: Implementation of Dropdown & It’s Demo for iOS Platform

In this step, we will see how to use the view in Xamarin.Forms.

  • Open your designer file and in my case MainPage.xaml and add the control as shown below.
    <local:Dropdown HorizontalOptions="FillAndExpand"
                    VerticalOptions="Center"
                    BackgroundColor="LawnGreen"
                    x:Name="dropdown"/>
  • Set ItemsSource and SelectedIndex as shown in below.
    dropdown.ItemsSource = Items1;
    dropdown.SelectedIndex = 1;
  • Add item selection event to dropdown as shown in below.
    public MainPage()
    {
          //...
          dropdown.ItemSelected += OnDropdownSelected;
    }
    
    private void OnDropdownSelected(object sender, ItemSelectedEventArgs e)
    {
          label.Text = Items1[e.SelectedIndex];
    }

Full Code implementation of Dropdown in MainPage

Here, we will see the full code for Main Page.

namespace XF.Ctrls
{
    public partial class MainPage : ContentPage
    {
        List<string> Items1 = new List<string>();
        List<string> Items2 = new List<string>();
        bool IsItem1 = true;

        public MainPage()
        {
            InitializeComponent();

            for (int i = 0; i < 4; i++)
            {
                Items1.Add(i.ToString());
            }

            for (int i = 0; i < 10; i++)
            {
                Items2.Add(i.ToString());
            }

            dropdown.ItemsSource = Items1;
            dropdown.SelectedIndex = 1;
            dropdown.ItemSelected += OnDropdownSelected;
        }

        private void OnDropdownSelected(object sender, ItemSelectedEventArgs e)
        {
            label.Text = IsItem1 ? Items1[e.SelectedIndex] : Items2[e.SelectedIndex];
        }

        private void btn_Clicked(object sender, EventArgs e)
        {
            dropdown.ItemsSource = IsItem1 ? Items2 : Items1;
            dropdown.SelectedIndex = IsItem1 ? 5 : 1;
            IsItem1 = !IsItem1;
        }
    }
}

Demo

The following screens shows the output this tutorial and it is awesome to have this dropdown in Xamarin.Forms.

Platform

Screenshots

Android

iOS

This article covers the implementation of new dropdown control in iOS Platform. Refer my previous article for the implementation of Dropdown in Android Platform.

My plan is to create a dropdown control for supporting all platforms and offering this control as a standard plugin.

Download Code

You can download the code from GitHub. If you have doubt, feel free to post comment. If you like this article and is useful to you, do like, share the article & star the repository on GitHub.