Introduction to Placeholder for Picker in Xamarin

picker in xamarin

Xamarin is a magnificent platform that fulfills all the necessities of a mobile application whether it is to implement an impeccable layout look or retrieve coordinates on Android, iOS with Xamarin.Forms. No matter what, it helps you with limitless possibilities. In this blog, we will discuss how to use Placeholder for Picker in Xamarin.

What is Picker?

Picker is a view control for selecting an item in a list of data. Pickers have some properties to change text color, title, title color, etc. Let’s see some information about picker properties.

  • Title: This property is used to set the title of the picker control which default is null.
  • TitleColor: This property is used to set the color of the Title text.
  • TextColor: This property is used to set the color of the Text.
  • FontSize: This property is used to set the size of the font which default to -1.0.
  • FontAttribute: This property is used to set the text bold, underline, etc. which is default to None.
  • FontFamily: This property is used to set the font style which is default to null.
  • CharacterSpacing: This property is used to do spacing between characters of picker item.
  • TextAlignment: This property is used to set the text alignment horizontal or vertical.
  • ItemsSource: This property is used to display a list of items that default to null. And Itemsource is a type of IList.
  • SelectedIndex: This property is working on the index of the selected item which is default to -1.
  • SelectedItem: This property is used to select an item from the list of data that default to null.

Now, let’s create a simple picker example after that we can create a project for a placeholder in the picker.

Step: 1

First, create a Xamarin application for both the platform Android and iOS.

Step: 2

After creating a project open MainPage.Xaml page and add a picker control and buttons and create a design as per your requirements.

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”

             x:Class=”PlaceholderForPicker.MainPage”>

    <StackLayout>

        <Grid>

            <Grid.ColumnDefinitions>

                <ColumnDefinition Width=”*”/>

                <ColumnDefinition Width=”*”/>

            </Grid.ColumnDefinitions>

            <Picker Title=”Title”

                    x:Name=”picker”

                    Grid.Row=”0″

                    Grid.Column=”0″

                    Grid.ColumnSpan=”2″/>

            <Button Text=”Picker:Set Index 1″

                    HorizontalOptions=”Center”

                    VerticalOptions=”Center”

                    Clicked=”Button_Clicked”

                    Grid.Row=”1″

                    Grid.Column=”0″/>

            <Button Text=”Picker:Set Default”

                    HorizontalOptions=”Center”

                    VerticalOptions=”Center”

                    Clicked=”Button_Clicked_1″

                    Grid.Row=”1″

                    Grid.Column=”1″/>

        </Grid>

    </StackLayout>

</ContentPage>

Here, we can add a picker for selecting an item from the list of data and two buttons, the first button for the set index, and the second button is for the clear selected item.

Step: 3

Now, open MainPage.Xaml.cs file and add the below code.

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Xamarin.Forms;

namespace PlaceholderForPicker

{

    public partial class MainPage : ContentPage

    {

        public MainPage()

        {

            InitializeComponent();

            List<string> items = new List<string>();

            items.Add(“Item 1”);

            items.Add(“Item 2”);

            picker.ItemsSource = items;

        }

        private void Button_Clicked(object sender, EventArgs e)

        {

            picker.SelectedIndex = 1;

        }

        private void Button_Clicked_1(object sender, EventArgs e)

        {

            picker.SelectedIndex = -1;

        }

    }

}

First of all, here we can create a list and add some data in the list, and set list data in picker using ItemSource property. And on the first button click event, we can set index 1 data, and on the second button click event, we can set index -1 this will clear the data from the picker.

Output:

Now, we can create an example of using a placeholder in picker control.

Step: 1

Open the Xaml page and add the below 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:d=”http://xamarin.com/schemas/2014/forms/design”

             xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″

             xmlns:local=”clr-namespace:PlaceholderForPicker”

             mc:Ignorable=”d”

             x:Class=”PlaceholderForPicker.MainPage”>

    <StackLayout>

        <Grid>

            <Grid.ColumnDefinitions>

                <ColumnDefinition Width=”*”/>

                <ColumnDefinition Width=”*”/>

            </Grid.ColumnDefinitions>

            <local:PickerClass  Placeholder=”Placeholder”

                                Title=”Title”

                                TitleColor=”Red”

                                x:Name=”picker”

                                Grid.Row=”0″

                                Grid.Column=”0″

                                Grid.ColumnSpan=”2″/>

            <Button Text=”Picker:Set Index 1″

                    HorizontalOptions=”Center”

                    VerticalOptions=”Center”

                    Clicked=”Picker_Clicked”

                    Grid.Row=”1″

                    Grid.Column=”0″/>

            <Button Text=”Picker:Set Default”

                    HorizontalOptions=”Center”

                    VerticalOptions=”Center”

                    Clicked=”Picker1_Clicked”

                    Grid.Row=”1″

                    Grid.Column=”1″/>

        </Grid>

    </StackLayout>

</ContentPage>

Here, we can add a namespace for using a placeholder in the picker.

Step: 2

MainPage.Xaml.cs

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Xamarin.Forms;

namespace PlaceholderForPicker

{

    public partial class MainPage : ContentPage

    {

        public MainPage()

        {

            InitializeComponent();

            List<string> items = new List<string>();

            items.Add(“Item 1”);

            items.Add(“Item 2”);

            picker.ItemsSource = items;

        }

        private void Picker_Clicked(object sender, EventArgs e)

        {

            picker.SelectedIndex = 1;

        }

        private void Picker1_Clicked(object sender, EventArgs e)

        {

            picker.SelectedIndex = -1;

        }

    }

}

Step: 3

You need to install two packages. Go to tools -> NuGet Package Manager -> Manage NuGet Packages for a solution and search for Xamarin.Android.Support.Core.Utils and install it for android. And add Xamarin.Android.Support.CustomTabs package for android.

Step: 4

After adding a button click event, we need to create a class for the picker on the main project.

PickerClass.cs

using System;

using System.Collections.Generic;

using System.Text;

using Xamarin.Forms;

namespace PlaceholderForPicker

{

    public class PickerClass : Picker

    {

        public static readonly BindableProperty PlaceholderPro = BindableProperty.Create(

            propertyName: nameof(Placeholder),

            returnType: typeof(string),

            declaringType: typeof(string),

            defaultValue: string.Empty);

        public string Placeholder

        {

            get

            {

                return (string)GetValue(PlaceholderPro);

            }

            set

            {

                SetValue(PlaceholderPro, value);

            }

        }

    }

}

Step: 5

After adding the picker class, we need to create one more file in the Android project. Here we can create a renderer file for Android picker.

using System.ComponentModel;

using Android.Content;

using PickerPlaceholder;

using PickerPlaceholder.Droid;

using PlaceholderForPicker;

using Xamarin.Forms;

using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(PickerClass), typeof(PLPickerRenderer))]

namespace PickerPlaceholder.Droid

{

    public class PLPickerRenderer : Xamarin.Forms.Platform.Android.AppCompat.PickerRenderer

    {

        PickerClass picker = null;

        public PLPickerRenderer(Context context) : base(context)

        {

        }

        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)

        {

            base.OnElementChanged(e);

            if (e.NewElement != null)

            {

                picker = Element as PickerClass;

                UpdatePickerPlaceholder();

                if (picker.SelectedIndex <= -1)

                {

                    UpdatePickerPlaceholder();

                }

            }

        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)

        {

            base.OnElementPropertyChanged(sender, e);

            if (picker != null)

            {

                if (e.PropertyName.Equals(PickerClass.PlaceholderPro.PropertyName))

                {

                    UpdatePickerPlaceholder();

                }

            }

        }

        protected override void UpdatePlaceHolderText()

        {

            UpdatePickerPlaceholder();

        }

        void UpdatePickerPlaceholder()

        {

            if (picker == null)

                picker = Element as PickerClass;

            if (picker.Placeholder != null)

                Control.Hint = picker.Placeholder;

        }

    }

}

Step: 6

Here, we can create a renderer for iOS. Open an iOS project and create a class and add the below code.

using System.ComponentModel;

using PickerPlaceholder;

using PickerPlaceholder.iOS;

using Xamarin.Forms;

using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(PLPicker), typeof(PLPickerRenderer))]

namespace PickerPlaceholder.iOS

{

    public class PLPickerRenderer: PickerRenderer

    {

        PLPicker picker = null;

        protected override void OnElementChanged(ElementChangedEventArgs<Picker> e)

        {

            base.OnElementChanged(e);

            if (e.NewElement != null)

            {

                picker = Element as PLPicker;

                UpdatePickerPlaceholder();

                if (picker.SelectedIndex <= -1)

                {

                    UpdatePickerPlaceholder();

                }

            }

        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)

        {

            base.OnElementPropertyChanged(sender, e);

            if (picker != null)

            {

                if (e.PropertyName.Equals(PLPicker.PlaceholderProperty.PropertyName))

                {

                    UpdatePickerPlaceholder();

                }

            }

        }

        void UpdatePickerPlaceholder()

        {

            if (picker == null)

                picker = Element as PLPicker;

            if (picker.Placeholder != null)

                Control.Placeholder = picker.Placeholder;

        }

    }

}

Output:

Conclusion

In this blog, we have learned about picker. With this view control, we have practically learnt how to select an item from the list. We have also used a placeholder in Xamarin forms for picker control. In Xamarin forms, picker control is a combination of AlertDialogBox and TextField.

Author Bio:

Ajay Patel – Technical Director, iFour Technolab USA. Inc.

A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. With sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop and Mobile solutions and is heading the technical department at Mobile Application Development Company – iFour Technolab USA. Inc

Leave a Reply

Your email address will not be published. Required fields are marked *