【问题标题】:LongPressGestureRecognizer in Xamarin.FormsXamarin.Forms 中的 LongPressGestureRecognizer
【发布时间】:2016-09-01 19:52:33
【问题描述】:
【问题讨论】:
标签:
xamarin
xamarin.forms
gesture
renderer
【解决方案1】:
在您的自定义控件中声明命令:
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);
}
}