Xamarin Forms 给视图添加标签

5
我是一名有用的助手,可以为您翻译文本。
我有一个关于图像按钮的问题,我希望我的函数“Categorie_Onclick”能够知道哪个按钮被点击了。我尝试过添加标签,但没有成功。有没有什么方法可以做到这一点?
XAML:
<!-- Button1 -->
<Image
  x:Name="CityGuideButton1"
  Source="shopping_gray.png"
  Aspect="Fill"
  HorizontalOptions="FillAndExpand"
  VerticalOptions ="FillAndExpand"
  Tag="01">
  <Image.GestureRecognizers>
    <TapGestureRecognizer
      Tapped="Categorie_Onclick"
      NumberOfTapsRequired="1"/>
  </Image.GestureRecognizers>
</Image>

<!-- Button2 -->
<Image
  x:Name="CityGuideButton2"
  Source="secrets.png"
  Aspect="Fill"
  HorizontalOptions="FillAndExpand"
  VerticalOptions ="FillAndExpand"
  Tag="02">
<Image.GestureRecognizers>
  <TapGestureRecognizer
    Tapped="Categorie_Onclick"
    NumberOfTapsRequired="1"/>
</Image.GestureRecognizers>
private async void Categorie_Onclick(Object sender, EventArgs args)
{
    Image cmd = sender as Image;
    string txt = TapGestureRecognizer.tag.ToString();
    await Navigation.PushAsync(new CategoriePage());
}
2个回答

15

你可以滥用 StyleIdClassId 或者 AutomationId 来实现此功能,但这是不好的,不要这样做。

最干净的方法是定义一个附加的BindableProperty。你可以在想要的类中定义它。

public class Foo {
    public static readonly BindableProperty TagProperty = BindableProperty.Create("Tag", typeof(string), typeof(Foo), null);

    public static string GetTag(BindableObject bindable)
    {
        return (string)bindable.GetValue(TagProperty);
    }

    public static void SetTag(BindableObject bindable, string value)
    {
        bindable.SetValue(TagProperty, value);
    }
}

那么您可以在 Xaml 中设置此标记。

<Image ... local:Foo.Tag="button1" />

并从您的事件处理程序中获取该标签

async void Categorie_Onclick(Object sender, EventArgs args)
{
    Image cmd = sender as Image;
    string txt = Foo.GetTag(cmd);
    await Navigation.PushAsync(new CategoriePage());
}

你可能会想知道为什么这个功能没有内置于平台中。嗯,这很可能是因为使用适当的Mvvm,这将不需要。


谢谢您的回答,但我有一个小问题,使用Mvvm更好吗?我是Xamarin的新手,以前从未使用过Mvvm。 - N. Smeding
通常最好使用Mvvm。但总有一些情况下,这种东西可能会有所帮助。 - Stephane Delcroix

1
首先,你的“tag”属性属于Image,而不是TapGestureRecognizer。不幸的是,在Xamarin.Forms中没有“tag”属性,但你可以使用StyleId,这通常用于UITesting。所以:
在XAML中,你的Image属性之一:
StyleId="02"

在Categorie_Onclick方法内,您可以像这样访问它:

cmd.StyleId; //following your naming

但作为最佳解决方案,我建议切换到MVVM和命令


对于这个小项目,我不需要使用MVVM。 - N. Smeding
相信在某个时候你会意识到该使用 MVVM 了。我建议使用自定义的 ContentPage 和 OnAppearing ContentPage 方法上的模型绑定来创建自己的 MVVM。非常简单,但是您可以根据需要进行扩展并在任何地方重用。 - valentasm

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接