Xamarin.Forms中的LongPressGestureRecognizer

时间:2016-09-01 09:43:19

标签: xamarin xamarin.forms gesture renderer

我正在向我的Label控件应用手势功能。我使用了这个链接 - http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/

当我长按标签控件时,我能够获得LongPressGestureRecognizer事件。此事件将在渲染器文件中调用。

我想在LongPressGestureRecognizer事件的共享代码中执行一些操作。那么如何在共享代码中检测到此事件?如何处理事件处理程序以在我的共享代码中获取此longpress事件?

1 个答案:

答案 0 :(得分:0)

在自定义控件声明命令中:

public class TappedGrid : Grid
{
    public static readonly BindableProperty TappedCommandProperty =
        BindableProperty.Create(nameof(TappedCommand),
                        typeof(ICommand),
                        typeof(TappedGrid),
                        default(ICommand));

    public ICommand TappedCommand
    {
        get { return (ICommand)GetValue(TappedCommandProperty); }
        set { SetValue(TappedCommandProperty, value); }
    }

    public static readonly BindableProperty LongPressCommandProperty =
        BindableProperty.Create(nameof(LongPressCommand),
                                typeof(ICommand),
                                typeof(TappedGrid),
                                default(ICommand));

    public ICommand LongPressCommand
    {
        get { return (ICommand)GetValue(LongPressCommandProperty); }
        set { SetValue(LongPressCommandProperty, value); }
    }
}

然后从渲染器中提出此命令:

public class TappedGridRenderer : ViewRenderer
{
    UITapGestureRecognizer tapGesturesRecognizer;
    UILongPressGestureRecognizer longPressGesturesRecognizer;

    protected override void OnElementChanged(ElementChangedEventArgs<View> e)
    {
        base.OnElementChanged(e);

        tapGesturesRecognizer = new UITapGestureRecognizer(() =>
        {
            var grid = (TappedGrid)Element;
            if (grid.TappedCommand.CanExecute(Element.BindingContext))
            {
                grid.TappedCommand.Execute(Element.BindingContext);
            }
        });

        longPressGesturesRecognizer = new UILongPressGestureRecognizer(() =>
        {
            var grid = (TappedGrid)Element;
            if (longPressGesturesRecognizer.State == UIGestureRecognizerState.Ended &&
                    grid.LongPressCommand.CanExecute(Element.BindingContext))
            {
                grid.LongPressCommand.Execute(Element.BindingContext);
            }
        });

        this.RemoveGestureRecognizer(tapGesturesRecognizer);
        this.RemoveGestureRecognizer(longPressGesturesRecognizer);

        this.AddGestureRecognizer(tapGesturesRecognizer);
        this.AddGestureRecognizer(longPressGesturesRecognizer);
    }
}