しっぽを追いかけて

ぐるぐるしながら考えています

Unity と猫の話題が中心   掲載内容は個人の私見であり、所属組織の見解ではありません

ダブルタップで Xamarin.Forms の ScrollView の拡縮を切り替えてみたい(失敗)

Xamarin.Forms には ScrollView というスクロール可能なレイアウトがありますが、Windows ランタイムのような拡大縮小機能がありません

何とかできないかビヘイビアを作って試してみました

/// <summary>
/// タップで拡大縮小する Behavior
/// </summary>
public class TapZoomBehavior : Behavior<ScrollView>
{
    /// <summary>
    /// アタッチされた View
    /// </summary>
    private ScrollView bindable = null;

    /// <summary>
    /// タップ GestureRecognizer
    /// </summary>
    private TapGestureRecognizer gestureRecognizer = null;

    /// <summary>
    /// Behavior がアタッチされた時の処理
    /// </summary>
    /// <param name="bindable">アタッチされた View</param>
    protected override void OnAttachedTo(ScrollView bindable)
    {
        base.OnAttachedTo(bindable);

        if (this.gestureRecognizer == null)
        {
            this.gestureRecognizer = new TapGestureRecognizer();
            this.gestureRecognizer.NumberOfTapsRequired = 2;
            this.gestureRecognizer.Tapped += this.OnGestured;
        }

        this.bindable = bindable;
        if (this.bindable == null)
        {
            return;
        }
        this.bindable.GestureRecognizers.Add(this.gestureRecognizer);
    }

    /// <summary>
    /// GestureRecognizer のイベントハンドラ
    /// </summary>
    /// <param name="sender">イベント発行者</param>
    /// <param name="args">イベント引数</param>
    private void OnGestured(object sender, EventArgs args)
    {
        // アタッチされた View に Setter を反映
        if (this.bindable.Scale == 1d)
        {
            this.bindable.Scale = 2d;
        }
        else
        {
            this.bindable.Scale = 1d;
        }
    }

    /// <summary>
    /// Behavior がデタッチされた時の処理
    /// </summary>
    /// <param name="bindable"></param>
    protected override void OnDetachingFrom(ScrollView bindable)
    {
        if (this.bindable != null && this.gestureRecognizer != null)
        {
            this.bindable.GestureRecognizers.Remove(this.gestureRecognizer);
            this.gestureRecognizer.Tapped -= this.OnGestured;
            this.gestureRecognizer = null;
            this.bindable = null;
        }
        base.OnDetachingFrom(bindable);
    }
}

なんてことないビヘイビアで Scale を切り替えるビヘイビア

次に 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:b="clr-namespace:XamarinControl.Behaviors;assembly=XamarinControl"
             x:Class="XamarinControl.Views.TopPage">

  <ScrollView>
    <ScrollView.Behaviors>
       <b:TapZoomBehavior/>
    </ScrollView.Behaviors>

    <Image Source="http://upload.wikimedia.org/wikipedia/commons/8/87/Norwegische_Waldkatze.jpg"/>

  </ScrollView>

</ContentPage>

とりあえず ScrollView の内部に画像を置いてビヘイビアをセット

f:id:matatabi_ux:20150208230256j:plain

ダブルタップで拡大縮小は切り替わりました・・・が、スクロール領域が広がらないので失敗;

やっぱりもっとちゃんと作らないとだめみたいです!