有没有办法模拟按钮的点击?

时间:2018-01-29 12:41:46

标签: xamarin xamarin.forms

我正在使用此代码创建一个看起来像按钮的东西:

 <Grid Grid.Column="0" ColumnSpacing="0" Margin="0,0,10,0">

    <Frame Grid.Column="0" CornerRadius="5" OutlineColor="Black">
      <Label  x:Name="faveIconLabel" Style="{StaticResource mediumIcon}" Margin="0,2,0,0" HorizontalOptions="Fill" FontFamily="FontAwesome" VerticalOptions="Center" VerticalTextAlignment="Center" />
    </Frame>

    <Frame Grid.Column="1" CornerRadius="5" OutlineColor="Black">
      <Label x:Name="hiddenIconLabel" Style="{StaticResource mediumIcon}" Margin="0,2,0,0" HorizontalOptions="Fill" FontFamily="FontAwesome" VerticalOptions="Center" VerticalTextAlignment="Center" />
    </Frame>

  </Grid>

有没有办法让我可以模拟点击事件,让它看起来像点击标签时实际上被按下的东西?

2 个答案:

答案 0 :(得分:2)

您可以将TapGestureRecognizer添加到几乎任何VisualElement,包括标签,图像等。

faveIconLabel.GestureRecognizers.Add(new TapGestureRecognizer((view) => OnLabelClicked()));

答案 1 :(得分:2)

如果您不想使用自定义渲染器,一种简单的方法是更改​​handleClick中的背景颜色,然后在几毫秒后将其恢复为原始颜色。例如,

private void handleClick(object sender, EventArgs e) {
    var view = (View)sender;
    view.BackgroundColor = Color.FromHex("#DD000000");

    Device.StartTimer(
        TimeSpan.FromMilliseconds(100), 
        () => 
        {
            // Revert it back to the original color, whatever it may be.
            Device.BeginInvokeOnMainThread(() => 
            {
                view.BackgroundColor = Color.Transparent; 
            });

            return false; // return false to prevent the timer from calling again
        });
}