在选择器中添加项目的键值 [英] Adding key values for items in picker
问题描述
我正在使用XAMARIN选择器选择一个国家.这些国家/地区在选择器中进行了硬编码.有没有一种方法可以通过键值识别每个国家/地区名称.我使用SAPUI5以类似的方式完成了此操作.
I am using a XAMARIN picker to select a country. The countries are hard coded in the picker. Is there a way I could identify each country name through a key value. I have done this in a similar way using SAPUI5.
<core:Item key="AF" text="Afghanistan " />
<core:Item key="AL" text="Albania " />
<core:Item key="DZ" text="Algeria " />
<core:Item key="VI" text="Amer.Virgin Is. " />
在某种意义上,我有没有办法在XAMARIN表单选择器中为每个国家/地区添加键值?
Similarily, is there a way for me to add a key value for each country in XAMARIN form picker?
推荐答案
否,xamarin选择器中的键属性可用.但是,您可以使用xamarin选择器类的Dictionary类和SelectedIndex属性来实现它.
No, Key property is available in xamarin picker. But, you can implement it using Dictionary class and SelectedIndex property of xamarin picker class.
通过使用以下代码片段进行实施:
class PickerDemoPage : ContentPage
{
// Dictionary to get Color from color name.
Dictionary<string, Color> nameToColor = new Dictionary<string, Color>
{
{ "Aqua", Color.Aqua }, { "Black", Color.Black },
{ "Blue", Color.Blue }, { "Fuschia", Color.Fuschia },
{ "Gray", Color.Gray }, { "Green", Color.Green },
{ "Lime", Color.Lime }, { "Maroon", Color.Maroon },
{ "Navy", Color.Navy }, { "Olive", Color.Olive },
{ "Purple", Color.Purple }, { "Red", Color.Red },
{ "Silver", Color.Silver }, { "Teal", Color.Teal },
{ "White", Color.White }, { "Yellow", Color.Yellow }
};
public PickerDemoPage()
{
Label header = new Label
{
Text = "Picker",
FontSize = Device.GetNamedSize (NamedSize.Large, typeof(Label)),
HorizontalOptions = LayoutOptions.Center
};
Picker picker = new Picker
{
Title = "Color",
VerticalOptions = LayoutOptions.CenterAndExpand
};
foreach (string colorName in nameToColor.Keys)
{
picker.Items.Add(colorName);
}
// Create BoxView for displaying picked Color
BoxView boxView = new BoxView
{
WidthRequest = 150,
HeightRequest = 150,
HorizontalOptions = LayoutOptions.Center,
VerticalOptions = LayoutOptions.CenterAndExpand
};
picker.SelectedIndexChanged += (sender, args) =>
{
if (picker.SelectedIndex == -1)
{
boxView.Color = Color.Default;
}
else
{
string colorName = picker.Items[picker.SelectedIndex];
boxView.Color = nameToColor[colorName];
}
};
// Accomodate iPhone status bar.
this.Padding = new Thickness(10, Device.OnPlatform(20, 0, 0), 10, 5);
// Build the page.
this.Content = new StackLayout
{
Children =
{
header,
picker,
boxView
}
};
}
}
来源: https://developer.xamarin.com/api/type/Xamarin.Forms.Picker/
这篇关于在选择器中添加项目的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!