ぴーさんログ

だいたいXamarin.Formsのブログ

【Xamarin.Forms 2.3.4-pre】ちゃんとBindableになったPicker

Xamarin.Forms 2.3.4-preでPickerがItemsSourceとItemSelectedをサポートするようになります。すっごーい!

さっそくこんな感じのViewModelを用意してContentPageのBindingContextにセットします。

public class ViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public IEnumerable<AnimalFriend> Friends { get; }

    AnimalFriend _bestFirend;
    public AnimalFriend BestFriend
    {
        get { return _bestFirend; }
        set
        {
            _bestFirend = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(BestFriend)));
        }
    }

    public ViewModel()
    {
        Friends = new[]{
            new AnimalFriend { Name = "サーバル" },
            new AnimalFriend { Name = "ジャガー" },
            new AnimalFriend { Name = "トキ"},
            new AnimalFriend { Name = "ツチノコ"},
        };
    }
}

public class AnimalFriend
{
    public string Name { get; set; }
}

ContentPageの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"
             x:Class="XFApp44.BindablePickerPage">
    <ContentPage.Content>
        <StackLayout Padding="15, 40, 15, 20">
            <Picker HeightRequest="40"
                    Title="いちばんのともだちをおしえてね"
                    ItemsSource="{Binding Friends}"
                    ItemDisplayBinding="{Binding Name, StringFormat='{0}ちゃん'}"
                    SelectedItem="{Binding BestFriend, Mode=OneWayToSource}"/>
            <Label Text="{Binding BestFriend.Name, StringFormat='{0}ちゃんととっても仲良しなんだね、すっごーい!'}" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

ItemsSourceの各アイテムをPickerに表示する際にはPicker.ItemDisplayBindingを使って適切なプロパティPathを指定することが可能です。 Binding構文で指定するのでStringFormatも使えます。かしこーい。

f:id:ticktack623:20170207011818j:plain