Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding key values for items in picker

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?

like image 336
anslem arnolda Avatar asked May 06 '16 10:05

anslem arnolda


1 Answers

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

like image 131
Michael Dahl Avatar answered Sep 18 '22 07:09

Michael Dahl