我的图像按钮出现问题我想要点击按钮看看我的功能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());
}
答案 0 :(得分:7)
你可能滥用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中设置这个标签
<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,这不是必需的。
答案 1 :(得分:-1)
首先,您的“tag”属性属于Image,而不是TapGestureRecognizer。不幸的是,Xamarin.Forms中没有“tag”属性,但你可以使用主要用于UITesting的StyleId。所以:
XAML中的一个Image属性:
StyleId="02"
在Categorie_Onclick方法中,您可以像这样访问它:
cmd.StyleId; //following your naming
但作为最佳解决方案,我建议切换到MVVM and Commands。