专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

添加点击手势识别器TapGestureRecognizer

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 0:56:41       共计:3590 浏览

点击手势用于点击检测,可通过 TapGestureRecognizer 类实现。


若要让某个用户界面元素可以使用点击手势进行点击,请创建 TapGestureRecognizer 实例,处理 Tapped 事件,并将新的手势识别器添加到该用户界面元素上的 GestureRecognizers 集合。 以下代码示例展示了附加到 Image 元素的 TapGestureRecognizer:

C#


var tapGestureRecognizer = new TapGestureRecognizer();

tapGestureRecognizer.Tapped += (s, e) => {

   // handle the tap

};

image.GestureRecognizers.Add(tapGestureRecognizer);


默认情况下,该图像将响应单击。 请将 NumberOfTapsRequired 属性设置为等待双击(必要时可设置为等待更多次点击)。

C#


tapGestureRecognizer.NumberOfTapsRequired = 2; // double-tap


当 NumberOfTapsRequired 设置为高于 1 时,只有在设定的时间段(此时间段不可配置)内进行点击时才会执行事件处理程序。 如果在该时间段内没有进行第二次(或后续)点击,系统会有效地忽略它们并重新启动“点击计数”。

使用 XAML


可以使用附加属性将手势识别器添加到 XAML 中的控件。 向图像添加 TapGestureRecognizer 的语法如下所示(在本例中定义了 双击 事件):

XAML


<Image Source="tapped.jpg">

   <Image.GestureRecognizers>

       <TapGestureRecognizer

               Tapped="OnTapGestureRecognizerTapped"

               NumberOfTapsRequired="2" />

 </Image.GestureRecognizers>

</Image>


事件处理程序的代码(在示例中)对计数器进行递增,并将图像从彩色更改为黑色和白色&。

C#


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


使用模型-视图-视图模型 (MVVM) 模式的应用程序通常使用 ICommand,而不是直接绑定事件处理程序。 TapGestureRecognizer 可轻松地支持 ICommand,方法为在代码中设置绑定:

C#


var tapGestureRecognizer = new TapGestureRecognizer();

tapGestureRecognizer.SetBinding (TapGestureRecognizer.CommandProperty, "TapCommand");

image.GestureRecognizers.Add(tapGestureRecognizer);


或使用 XAML:

XAML


<Image Source="tapped.jpg">

   <Image.GestureRecognizers>

       <TapGestureRecognizer

           Command="{Binding TapCommand}"

           CommandParameter="Image1" />

   </Image.GestureRecognizers>

</Image>


可以在示例中找到此视图模型的完整代码。 相关的 Command 实现细节如下所示:

C#


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

}


相关链接


   TapGesture(示例)

   GestureRecognizer

   TapGestureRecognizer



版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:Xamarin.Forms TapGestureRecognizer 实现点击事件 | ·下一条:Xamarin.Forms Android PDA 监听手机按键

Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有