タップ ジェスチャ認識エンジンを追加する

Download Sampleサンプルのダウンロード

タップ ジェスチャはタップ検出に使用され、TapGestureRecognizer クラスで実装されています。

ユーザー インターフェース要素をタップ ジェスチャを使用してクリックできるようにするには、TapGestureRecognizer インスタンスを作成し、Tapped イベントを処理し、新しいジェスチャ認識エンジンをユーザー インターフェイス要素の GestureRecognizers コレクションに追加します。 次に示すのは、Image 要素に関連付けられている TapGestureRecognizer のコード例です。

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.Tapped += (s, e) => {
    // handle the tap
};
image.GestureRecognizers.Add(tapGestureRecognizer);

既定で、画像は 1 回のタップに応答します。 ダブルタップ (または必要に応じてより多くのタップ) を待機するように NumberOfTapsRequired プロパティを設定します。

tapGestureRecognizer.NumberOfTapsRequired = 2; // double-tap

NumberOfTapsRequired を 1 を超える値に設定すると、設定された期間内にタップが発生した場合にのみ、イベント ハンドラーが実行されます (この期間は構成できません)。 2 回目 (またはそれ以降の) タップがその期間内に発生しない場合は、実質的に無視され、'タップのカウント' が再開されます。

Xaml を使用する

ジェスチャ認識エンジンは、添付プロパティを使用して Xaml のコントロールに追加できます。 画像に TapGestureRecognizer を追加する構文を以下に示します (この例では、ダブル タップ イベントを定義します)。

<Image Source="tapped.jpg">
    <Image.GestureRecognizers>
        <TapGestureRecognizer
                Tapped="OnTapGestureRecognizerTapped"
                NumberOfTapsRequired="2" />
  </Image.GestureRecognizers>
</Image>

(サンプル内の) イベント ハンドラーのコードはカウンターをインクリメントし、イメージを色から黒と白に変更します。

void OnTapGestureRecognizerTapped(object sender, EventArgs args)
{
    tapCount++;
    var imageSender = (Image)sender;
    // watch the monkey go from color to black&white!
    if (tapCount % 2 == 0) {
        imageSender.Source = "tapped.jpg";
    } else {
        imageSender.Source = "tapped_bw.jpg";
    }
}

ICommand の使用

Model-View-ViewModel (MVVM) パターンを使用するアプリケーションでは、通常、イベント ハンドラーを直接接続するのではなく、ICommand を使用します。 TapGestureRecognizerICommand を簡単にサポートするには、次のようにコードにバインドを設定するか、

var tapGestureRecognizer = new TapGestureRecognizer();
tapGestureRecognizer.SetBinding (TapGestureRecognizer.CommandProperty, "TapCommand");
image.GestureRecognizers.Add(tapGestureRecognizer);

次のように Xaml を使用するします。

<Image Source="tapped.jpg">
    <Image.GestureRecognizers>
        <TapGestureRecognizer
            Command="{Binding TapCommand}"
            CommandParameter="Image1" />
    </Image.GestureRecognizers>
</Image>

このビュー モデルの完成したコードについては、サンプルを参照してください。 関連する Command 実装の詳細を以下に示します。

public class TapViewModel : INotifyPropertyChanged
{
    int taps = 0;
    ICommand tapCommand;
    public TapViewModel () {
        // configure the TapCommand with a method
        tapCommand = new Command (OnTapped);
    }
    public ICommand TapCommand {
        get { return tapCommand; }
    }
    void OnTapped (object s)  {
        taps++;
        Debug.WriteLine ("parameter: " + s);
    }
    //region INotifyPropertyChanged code omitted
}