LoginSignup
15
9

More than 5 years have passed since last update.

Xamarin.Forms 向けのピッカーコントロールを作った

Last updated at Posted at 2016-12-27

iOS の UIPickerView、 Android の NumberPicker は Xamarin.Forms では、標準コントロールで用意されていないみたいだったので Custom Renderer で作りました。

特に nuget パッケージとかにはしてなくて、サンプルアプリと一緒になってます(><)

こんな感じのコントロールです。

こんな感じで使えます。

ItemsSourceSelectedIndex の2つのバインダブルなプロパティしかなくて、SelectedIndex の方は TwoWay です。

<?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:PickerViewSample"
             x:Class="PickerViewSample.PickerViewSamplePage"
             Title="PickerView Sample">

    <ContentPage.BindingContext>
        <local:Model />
    </ContentPage.BindingContext>

    <ContentPage.Resources>
        <ResourceDictionary>
            <local:ItemsSourceConverter x:Key="itemsConv"/>
        </ResourceDictionary>
    </ContentPage.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="Auto" />
        </Grid.ColumnDefinitions>

        <local:PickerView
            Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3"
            ItemsSource="{Binding ItemsSource, Converter={StaticResource itemsConv}}"
            SelectedIndex="{Binding SelectedIndex}" />

        <Label Grid.Row="1" Grid.Column="0" Text="ItemsSource" />
        <Entry Grid.Row="1" Grid.Column="1" Text="{Binding ItemsSource, Mode=TwoWay}" />

        <Label Grid.Row="2" Grid.Column="0" Text="SelectedIndex" />
        <Entry Grid.Row="2" Grid.Column="1" Text="{Binding SelectedIndex, Mode=TwoWay}" />
    </Grid>
</ContentPage>

ソースコードは、

にありますので、 Fork などして使ってください。

iOS の UIPickerView は、それ自体が複数の列を持てるようですが、Android のはそうではないので、1列しか使ってません。

Custom Renderer のサンプルにもなると思います。

追記: PickerView を並べて数値を選択する UI も作った

ソースコードは上と同じギッハブにあります。

15
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
9