如何从我的选择器中获得价值?Xamarin形成

本文关键字:Xamarin 形成 我的 选择器 | 更新日期: 2023-09-27 18:28:28

我很难从选择器中取出选定的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];

现在,即使我选择了数字2,我也只能得到值"info1"。它与SelectedIndex有关,所以它只选择"1",但我不知道如何编写代码使其适用于所选项目。

如何从我的选择器中获得价值?Xamarin形成

您应该看看这个:

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

否则,在新版Xamarin表单2.3.4中存在

可绑定选取器

您可以设置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>