Xamarin.Forms 中的 LongPressGestureRecognizer

LongPressGestureRecognizer in Xamarin.Forms

我正在将手势功能应用于 Label 控件。我用过这个 link- http://arteksoftware.com/gesture-recognizers-with-xamarin-forms/

当我长按标签时,我能够得到 LongPressGestureRecognizer 事件 control.This 在渲染器文件中调用事件。

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

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

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);
    }
}