Adding key values for items in picker

前端 未结 3 1965
借酒劲吻你
借酒劲吻你 2021-02-07 12:34

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

3条回答
  •  [愿得一人]
    2021-02-07 12:41

    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

提交回复
热议问题