簡體   English   中英

如何將字典密鑰對放入xamarin表單中的選擇器中並從選擇器中檢索鍵值?

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

我有一個xaml文件,我把選擇器和后面的代碼填入其中。 使用的代碼如下:

 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);
            }

當我選擇黃色時,我試圖獲得值55,但我得到的唯一的東西是5.我使用它來獲取所選值

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

甚至可以獲得關鍵值? 已經查看了BindablePicker,但似乎根本沒有用。 非常感謝任何幫助。

我想你的意思是:

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

我建議熟悉MVVM,並在此特定情況下使用Behaviors 我寫了一個小例子來演示它如何使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM