简体   繁体   中英

How to get the value from my picker? Xamarin forms

I have trouble to get out the selected string from my picker. This is my code:

XAML:

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

CODE:

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

Now I only get the value "info1" even if i select number 2. It has something to do with the SelectedIndex so it only picks the "1", but I am not sure how to write the code to make it work for the selected item.

You should take a look at this :

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

Otherwise in new Xamarin Forms Release 2.3.4 exists the

Bindable Picker

you can set an ItemSource

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

and Bind the SelectedIndex property

SelectedIndex="{Binding CountriesSelectedIndex}"

XLabs is already providing it. Here is an example:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM