我的图像按钮有问题我希望我的函数 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());
}
最佳答案
您可以为此滥用 StyleId
、ClassId
或 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中设置这个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/