如何在ViewCell中创建一个标签,单击该标签时会调用方法?

时间:2017-08-24 16:30:23

标签: xamarin xamarin.forms

我有这段代码:

<ViewCell x:Name="ss" Height="50">
    <Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
        <Label Style="{DynamicResource ListItemTextStyle}" HorizontalOptions="StartAndExpand" VerticalOptions="Center" Text="Category Group" />
        <Switch x:Name="ssSwitch" HorizontalOptions="End" VerticalOptions="Center" Grid.Column="1" Toggled="SsSwitch" />
    </Grid>
</ViewCell>

我想用另一行和一个带有&#34; Clear Deck&#34;

文本的标签来扩展它

如何为此添加标签,点击后会调用方法?

1 个答案:

答案 0 :(得分:3)

这是一个如何做的简单示例。您只需添加一个带有TapGestureRecognizer的标签。然后,您需要在后面的代码中实现ClearLabelTapped

<ViewCell x:Name="ss" Height="50">
  <StackLayout Orientation="Vertical">
    <Grid VerticalOptions="CenterAndExpand" Padding="20, 0">
      <Label Style="{DynamicResource ListItemTextStyle}" HorizontalOptions="StartAndExpand" VerticalOptions="Center" Text="Category Group" />
      <Switch x:Name="ssSwitch" HorizontalOptions="End" VerticalOptions="Center" Grid.Column="1" Toggled="SsSwitch" />
    </Grid>
    <Label Text="Clear Deck">
      <Label.GestureRecognizers>
        <TapGestureRecognizer Tapped="ClearLabelTapped" />
      </Label.GestureRecognizers>
    </Label>
  </StackLayout>
</ViewCell>

代码背后:

public void ClearLabelTapped(object sender, EventArgs args) 
{
   // This is called when you tab the "Clear Deck" label
}

请注意,使用视图模型和命令是更好的方法(关注点分离),但我想保持这一点。请参阅how to work with the TapGestureRecognizer上的官方文档。