扩展 Label 控件 - 添加 Click 事件处理程序

Extend Label control - adding a Click event handler

我需要一个可以响应单击/点击和双击/点击的控件。我发现如果我想处理单击和双击/点击,我不能使用 TapGestureRecognizer。因此,我试图扩展一个 Label 控件,添加一个 Click 事件处理程序。我尝试了以下代码,但事件没有触发。有什么建议么?谢谢!

在LabelClickable.cs: ... public class LabelClickable:标签 { public 事件 EventHandler Clicked; public 虚拟无效 OnClicked() { 单击?.Invoke(this, EventArgs.Empty); } } ...<br> 在 MainPage.XAML 中: ... <local:LabelClickable Text="0" Clicked="Button_Clicked"/> ...<br> 在 MainPage.Xaml.cs 中: ... private void Button_Clicked(object sender, EventArgs e) { //做一点事; } ...

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

这是完整的工作解决方案(感谢 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 不需要其他任何内容。

对于单击和双击都非常有效!结果是一个显示计数器的可点击标签;计数器在单击时递增,在双击时递减。