Xamarin窗体为视图添加一个标签
本文关键字:一个 标签 窗体 视图 添加 Xamarin | 更新日期: 2023-09-27 18:13:00
我有一个问题与我的图像按钮,我想我的功能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
,但这是不好的,所以不要。
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,这将不需要。
首先,你的"tag"属性属于Image,而不是TapGestureRecognizer。不幸的是,Xamarin中没有"tag"属性。表单,但你可以使用StyleId,它主要用于测试。所以:
XAML中的一个图像属性:
StyleId="02"
在Categorie_Onclick方法中你可以这样访问它:
cmd.StyleId; //following your naming
但作为最好的解决方案,我建议切换到MVVM和命令。