Adding key values for items in picker

18,213

Solution 1

No, Key property is available in xamarin picker. But, you can implement it using Dictionary class and SelectedIndex property of xamarin picker class.

Implement it by using following code snippet :

class PickerDemoPage : ContentPage
        {
            // Dictionary to get Color from color name.
            Dictionary<string, Color> nameToColor = new Dictionary<string, Color>
            {
                { "Aqua", Color.Aqua }, { "Black", Color.Black },
                { "Blue", Color.Blue }, { "Fuschia", Color.Fuschia },
                { "Gray", Color.Gray }, { "Green", Color.Green },
                { "Lime", Color.Lime }, { "Maroon", Color.Maroon },
                { "Navy", Color.Navy }, { "Olive", Color.Olive },
                { "Purple", Color.Purple }, { "Red", Color.Red },
                { "Silver", Color.Silver }, { "Teal", Color.Teal },
                { "White", Color.White }, { "Yellow", Color.Yellow }
            };

            public PickerDemoPage()
            {
                Label header = new Label
                {
                    Text = "Picker",
                    FontSize = Device.GetNamedSize (NamedSize.Large, typeof(Label)),
                    HorizontalOptions = LayoutOptions.Center
                };

                Picker picker = new Picker
                {
                    Title = "Color",
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };

                foreach (string colorName in nameToColor.Keys)
                {
                    picker.Items.Add(colorName);
                }

                // Create BoxView for displaying picked Color
                BoxView boxView = new BoxView
                {
                    WidthRequest = 150,
                    HeightRequest = 150,
                    HorizontalOptions = LayoutOptions.Center,
                    VerticalOptions = LayoutOptions.CenterAndExpand
                };

                picker.SelectedIndexChanged += (sender, args) =>
                    {
                        if (picker.SelectedIndex == -1)
                        {
                            boxView.Color = Color.Default;
                        }
                        else
                        {
                            string colorName = picker.Items[picker.SelectedIndex];
                            boxView.Color = nameToColor[colorName];
                        }
                    };

                // Accomodate iPhone status bar.
                this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);

                // Build the page.
                this.Content = new StackLayout
                {
                    Children =
                    {
                        header,
                        picker,
                        boxView
                    }
                };

            }
        }

Source : https://developer.xamarin.com/api/type/Xamarin.Forms.Picker/

Solution 2

There is a way of using Key-Value-Pairs in a Picker using Data Binding.

First you have to define the Dictionary in the Form's View Model and define a Property which returns a List of the Dictionaries Key-Value-Pairs. Also a Binding to the currently selected Item is needed:

class MyViewModel
{
  ...
  private Dictionary<string, string> PickerItems = 
    new Dictionary<string, string>() { {"AF", "Afghanistan"}, {"AL", "Albania" } };

  public List<KeyValuePair<string, string>> PickerItemList
  {
      get => PickerItems.ToList();
  }

  private KeyValuePair<string, string> _selectedItem;
  public KeyValuePair<string, string> SelectedItem
  {
      get => _selectedItem;
      set => _selectedItem = value;
  }
  ...
}

Second you have to set the Pickers ItemsSource, ItemDisplayBinding and SelectedItem Bindings in the Pickers definition:

<Picker
    ItemDisplayBinding="{Binding Value}"
    ItemsSource="{Binding PickerItemList}"
    SelectedItem="{Binding SelectedItem}" />

Given this, you can get the key of the selected Item in the View Model via

SelectedItem.Key

Further Reading: https://developer.xamarin.com/guides/xamarin-forms/user-interface/picker/populating-itemssource/#Populating_a_Picker_with_Data_Using_Data_Binding

Solution 3

I was just facing the same problem and I found a way to do it. I just needed to bind a picker with a list of SomeClass elements. Here is what I did:

namespace MyApp.ViewModels 
{
    public class CboViewModel 
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}

And then in my XAML file:

<ContentPage ...
    xmlns:vm="clr-namespace:MyApp.ViewModels;assembly=Myapp" >
    <ContentPage.Content>
        ...
        <Picker x:Name="pckStatus" HorizontalOptions="FillAndExpand" >
            <Picker.ItemsSource>
                <x:Array Type="{x:Type vm:CboViewModel}" >
                    <vm:CboViewModel Id="0" Name="All" />
                    <vm:CboViewModel Id="1" Name="New" />
                    <vm:CboViewModel Id="2" Name="Standby" />
                    <vm:CboViewModel Id="4" Name="In Progress" />
                    <vm:CboViewModel Id="8" Name="Submitted" />
                    <vm:CboViewModel Id="16" Name="Closed" />
                </x:Array>
            </Picker.ItemsSource>
            <Picker.ItemDisplayBinding>
                <Binding Path="Name" />
            </Picker.ItemDisplayBinding>
            <Picker.SelectedIndex>0</Picker.SelectedIndex>
        </Picker>
        ...
    <ContentPage.Content>
</ContentPage>
Share:
18,213
anslem arnolda
Author by

anslem arnolda

As an astute and result oriented Professional, Anslem has a good understanding of IT domains in delivering business solutions, utilizing keen analysis and insights with team approaches to drive organizational process improvements and implementation of best practices etc. Anslem has a keen interest one modern technology and Digitalization where he many contributions were given at personal as well as organizational levels. Researching on technological inventions, working with modern applications, Cloud based and IOT solutions are certain topics that he shows interest on. He has extended expertise in trouble shooting, Software Development and Programming. As an SAP Consultant, he has gained experience in many business modules by working with multiple clients both locally and internationally. He is well versed with efficiently handling all activities and maintaining quality to the work entrusted to him by being methodical and having a keen eye for detail results in solid coding and trustworthy software programs. As a professional, he always dedicates himself as an ambitious personal to achieve organizational goals, while gaining working experience in high pressure environments with strict deadlines and multiple deliverable s.

Updated on June 09, 2022

Comments

  • anslem arnolda
    anslem arnolda about 2 years

    I am using a XAMARIN picker to select a country. The countries are hard coded in the picker. Is there a way I could identify each country name through a key value. I have done this in a similar way using SAPUI5.

    <core:Item key="AF" text="Afghanistan  " />
    <core:Item key="AL" text="Albania  " />
    <core:Item key="DZ" text="Algeria  " />
    <core:Item key="VI" text="Amer.Virgin Is. " />
    

    Similarily, is there a way for me to add a key value for each country in XAMARIN form picker?

  • Tim
    Tim over 6 years
    Excellent code sample. Still trying to fully understand how it all works together, but simplest example I could find. I was able to access the key and values of SelectedItem in the code behind pretty easily for anyone else that might want to do that.
  • Tim
    Tim over 6 years
    Add this property to the picker in the xaml, and then name any method. <Picker SelectedIndexChanged="OnPickerChangedEvent" /> Call that method in the xaml.cs public void OnPickerChangedEvent(object sender, EventArgs e) { var picker = (Picker)sender; var myIndex = picker.SelectedIndex; var myData = this.MyViewModel.SelectedItem.Key; }
  • pythlang
    pythlang over 5 years
    Excellent, simple example with clean code addressing the question directly. Thanks for the come-up; this should be the accepted answer