[英]Extend Label control - adding a Click event handler
我需要一个可以响应单击/点击和双击/点击的控件。 我发现如果我想同时处理单击和双击/点击,我就无法使用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; } ...
这是完整的工作解决方案(感谢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上不需要任何其他内容。
就像单个和双重水龙头的魅力一样! 结果是显示计数器的可点击标签; 计数器在单击时递增,在双击时递减。
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) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.