xamarin.formsdropdowncode-behindpickerbindable

How do I put a dictionary key pair into a picker in xamarin forms and retrieve the key value from the picker?


I have a xaml file where I put the picker in and a code behind to populate it. The code used below:

 Dictionary<string, int> list = new Dictionary<string, int>
            {
                { "Aqua", 6},
                { "Red", 1 },
                { "Silver", 2 },
                { "Teal", 3 },
                { "White", 4 },
                { "Yellow", 55 }
            };
            foreach (string item in list.Keys)
            {
                ddlPurpose.Items.Add(item);
            }

I am trying to get the value 55 when I select yellow but the only thing I get is 5. I am using this to get the selected value

var val1 = ddlPurpose.SelectedItem.ToString();
        var val2 = ddlPurpose.SelectedIndex;

Is it even possible to get the key value? Have looked into the BindablePicker but that didn't seem to work at all. Any help on this is greatly appreciated.


Solution

  • I guess what you meant to do is:

    var pSelectedIndex = ddlPurpose.SelectedIndex;
    var selectedKey = list.Values.ElementAt(pSelectedIndex);
    

    I would recommend to get familiar with MVVM and in this specific case with Behaviors. I wrote a small example to demonstrate how it may look using MVVM:

    public class PickerKeyValueTestViewModel : INotifyPropertyChanged
    {
        static Dictionary<string, int> colors { get; } = new Dictionary<string, int>
            {
                { "Aqua", 6 },
                { "Red", 1 },
                { "Silver", 2 },
                { "Teal", 3 },
                { "White", 4 },
                { "Yellow", 55 }
            };
    
        public List<string> Colors { get; } = colors.Keys.ToList();
    
        public string SelectedColor { get; set; }
    
        public void OnSelectedColorChanged()
        {
            if (string.IsNullOrEmpty(SelectedColor)) return;
            var selectedValue = colors[SelectedColor];
        }
    
        // Using PropertyChanged.Fody
        public event PropertyChangedEventHandler PropertyChanged;
    }
    
    <ContentPage
        xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:PickerKeyValueTest"
        x:Class="PickerKeyValueTest.PickerKeyValueTestPage">
    
        <ContentPage.BindingContext>
            <local:PickerKeyValueTestViewModel />
        </ContentPage.BindingContext>
    
        <StackLayout
            Margin="25">
            <Picker
                ItemsSource="{Binding Colors}"
                SelectedItem="{Binding SelectedColor}">
    
            </Picker>
        </StackLayout>
    </ContentPage>