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 t
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 PickerItems =
new Dictionary() { {"AF", "Afghanistan"}, {"AL", "Albania" } };
public List> PickerItemList
{
get => PickerItems.ToList();
}
private KeyValuePair _selectedItem;
public KeyValuePair SelectedItem
{
get => _selectedItem;
set => _selectedItem = value;
}
...
}
Second you have to set the Pickers ItemsSource, ItemDisplayBinding and SelectedItem Bindings in the Pickers definition:
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