c# - Xamarin Forms 向 View 添加标签

标签 c# xaml xamarin xamarin.forms

我的图像按钮有问题我希望我的函数 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());
}

最佳答案

您可以为此滥用 StyleIdClassIdAutomationId,但这很糟糕,所以不要这样做。

最简洁的方法是定义附加的 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中设置这个Tag

<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,就不需要这样做了。

关于c# - Xamarin Forms 向 View 添加标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40023414/

相关文章:

c# - Docker Copy 使用 ASP.net Core 失败

c# - Windows Mobile - 如何检查是否有 WIFI 连接?

c# - 将多种文件类型保存到一个文件中

Xamarin.iOS 生成错误 System.IO.FileNotFoundException

c# - 在我的 Xamarin.Forms PCL 项目中实现 FlyoutNavigation

android - 导入 Xamarin keystore - System.AggregateException

c# - 为什么没有捕获异常?

c# - 当不同程序集中的 App.xaml 时,Visual Studio 2012 XAML 设计器不显示正确的内容

c# - 如何绑定(bind)到嵌套类 wpf

c# - SQL Server 始终在插入时加密排序规则不兼容