我需要一个可以响应单击/点击和双击/点按的控件。我发现如果我想同时处理单击和双击/点击,我就无法使用TapGestureRecognizer。所以,我试图扩展一个Label控件,添加一个Click事件处理程序。我尝试了以下代码,但事件不会触发。有什么建议?谢谢!
in LabelClickable.cs:
...
public class LabelClickable : Label
{
public event EventHandler Clicked;
public virtual void OnClicked()
{
Clicked?.Invoke(this, EventArgs.Empty);
}
}
...
in MainPage.XAML:
...
<local:LabelClickable Text="0" Clicked="Button_Clicked"/>
...
and in MainPage.Xaml.cs:
...
private void Button_Clicked(object sender, EventArgs e)
{
//do something;
}
...
答案 0 :(得分:2)
这是完整的工作解决方案(感谢Jason的建议!):
public class LabelClickable: Label
{
public LabelClickable()
{
TapGestureRecognizer singleTap = new TapGestureRecognizer()
{
NumberOfTapsRequired = 1
};
TapGestureRecognizer doubleTap = new TapGestureRecognizer()
{
NumberOfTapsRequired = 2
};
this.GestureRecognizers.Add(singleTap);
this.GestureRecognizers.Add(doubleTap);
singleTap.Tapped += Label_Clicked;
doubleTap.Tapped += Label_Clicked;
}
private static int clickCount;
private void Label_Clicked(object sender, EventArgs e)
{
if (clickCount < 1)
{
TimeSpan tt = new TimeSpan(0, 0, 0, 0, 250);
Device.StartTimer(tt, ClickHandle);
}
clickCount++;
}
bool ClickHandle()
{
if (clickCount > 1)
{
Minus1();
}
else
{
Plus1();
}
clickCount = 0;
return false;
}
private void Minus1()
{
int value = Convert.ToInt16(Text) - 1;
if (value < 0)
value = 0;
Text = value.ToString();
}
private void Plus1()
{
Text = (Convert.ToInt16(Text) + 1).ToString();
}
}
MainPage.xaml上的用法:
<local:LabelClickable Text="0" Grid.Row="0" Grid.Column="0" BackgroundColor="Transparent" FontSize="Large" FontAttributes="Bold" HorizontalTextAlignment="Center"/>
MainPage.xaml.cs上不需要任何其他内容。
兼作单头和双头的魅力!结果是显示计数器的可点击标签;计数器在单击时递增,在双击时递减。
答案 1 :(得分:1)
TappedGestureRecognizer sng = new TappedGestureRecognizer();
TappedGestureRecognizer dbl = new TappedGestureRecognizer();
dbl.NumberOfTapsRequired = 2;
sng.Tapped += OnSingleTap;
dbl.Tapped += OnDoubleTap;
// assuming you're within a Control's context
this.GestureRecognizers.Add(sng);
this.GestureRecognizers.Add(dbl);
protected void OnSingleTap(object sender, EventArgs e) {
}
protected void OnDoubleTap(object sender, EventArgs e) {
}