Xaml 語法
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XFViewPractice"
x:Class="XFViewPractice.XF_Picker">
<ContentPage.Content>
<StackLayout
HorizontalOptions="Center"
VerticalOptions="Center">
<Label
Text="Picker Demo"
FontSize="Large"
HorizontalOptions="Center" />
<Picker
x:Name="ColorPicker"
Title="選擇顏色"
VerticalOptions="CenterAndExpand"
SelectedIndex="1"
SelectedIndexChanged="ColorPicker_SelectedIndexChanged">
<Picker.Items>
<x:String>Aqua</x:String>
<x:String>Black</x:String>
<x:String>Blue</x:String>
<x:String>Fucshia</x:String>
<x:String>Gray</x:String>
<x:String>Green</x:String>
<x:String>Lime</x:String>
<x:String>Maroon</x:String>
<x:String>Navy</x:String>
<x:String>Olive</x:String>
<x:String>Purple</x:String>
<x:String>Red</x:String>
<x:String>Silver</x:String>
<x:String>Teal</x:String>
<x:String>White</x:String>
<x:String>Yellow</x:String>
</Picker.Items>
<Picker.SelectedIndex>4</Picker.SelectedIndex>
</Picker>
<BoxView
x:Name="ColorDisplay"
WidthRequest="150"
HeightRequest="150"
HorizontalOptions="Center"
VerticalOptions="Center"></BoxView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
C# 語法
namespace XFViewPractice
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class XF_Picker : ContentPage
{
public XF_Picker()
{
InitializeComponent();
// 指定 Picker 初始值為灰色
// ColorPicker.SelectedIndex = 4;
}
private void ColorPicker_SelectedIndexChanged(object sender, EventArgs e)
{
if (sender is Picker ColorPicker)
{
int index = ColorPicker.SelectedIndex;
if (index == -1)
{
ColorDisplay.Color = Color.Default;
}
else
{
string colorName = ColorPicker.Items[index];
var converter = new ColorTypeConverter();
var Color = (Color)converter.ConvertFromInvariantString(colorName);
ColorDisplay.Color = Color;
}
}
}
}
}
筆記重點- Item:是一個 IList<string>
- 指定 Picker 初始值:在 xaml 內要指定初始值,要寫在 xaml 語法 highlight 38 行的位置,寫在 Higlight 18 行位置,會因為 Item 內還沒有資料,所以不會指定,也不會拋出 Exception 喔
- 顏色轉換:dotNet 內是透過 Color.FormName() 就可以把字串轉為 Color Type,在 Xamarin 內則是必須使用 ColorTypeConverter
執行 Picker 初始值為灰色
Picker 選單
選擇綠色
沒有留言:
張貼留言