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

时间:2015-12-28 23:28:17

标签: c# xamarin xamarin.forms

我无法从我的选择器中取出选定的string。 这是我的代码:

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

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

2 个答案:

答案 0 :(得分:12)

你应该看看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 Release 2.3.4中存在

Bindable Picker

你可以设置一个ItemSource

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

并绑定SelectedIndex属性

SelectedIndex="{Binding CountriesSelectedIndex}"

答案 1 :(得分:0)

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>