1

我有一个 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,但这似乎根本不起作用。非常感谢您对此的任何帮助。

4

1 回答 1

3

我猜你的意思是:

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>
于 2017-12-20T07:46:28.490 回答