如何从我的选择器中获取值? Xamarin 表单

How to get the value from my picker? Xamarin forms

我很难从我的选择器中取出 selected string。 这是我的代码:

XAML:

<Picker x:Name="thePicker" >
    <Picker.Items>
        <x:String>info1</x:String>
        <x:String>info2 </x:String>
    </Picker.Items>
</Picker>

代码:

thePicker.SelectedIndex = 1; //here is the problem i suppose, any idea what i should type?
var ourPickedItem = thePicker.Items[thePicker.SelectedIndex];

现在我只得到值"info1"即使我select数字2。它与SelectedIndex有关所以它只选择“1”,但我我不确定如何编写代码以使其适用于 selected 项目。

你应该看看 this:

picker.SelectedIndexChanged += (sender, args) =>
{
    if (picker.SelectedIndex == -1)
    {
        boxView.Color = Color.Default;
    }
    else
    {
        string colorName = picker.Items[picker.SelectedIndex];
        boxView.Color = nameToColor[colorName];
    }
};

否则在新的 Xamarin Forms 版本 2.3.4 中存在

Bindable Picker

你可以设置一个 ItemSource

<Picker ItemsSource="{Binding Countries}" />

并绑定 SelectedIndex 属性

SelectedIndex="{Binding CountriesSelectedIndex}"

XLabs 已经提供了。这是一个例子:

<ContentPage x:Class="XLabs.Samples.Pages.Controls.ExtendedPickerPage"
         xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:controls="clr-namespace:XLabs.Forms.Controls;assembly=XLabs.Forms"
         Title="Picker">
<ContentPage.Content>
    <StackLayout x:Name="myStackLayout">
        <Label Text="Xaml:" />
        <controls:ExtendedPicker x:Name="myPicker"
                                 DisplayProperty="FirstName"
                                 ItemsSource="{Binding MyDataList}"
                                 SelectedItem="{Binding TheChosenOne}" />
    </StackLayout>
</ContentPage.Content>