Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xamarin Forms add a Tag to a View

I have a problem with my Image buttons i want that my function Categorie_Onclick can see with button is clicked. I tried this with adding Tags but it doesnt work. Is there a way to do this?

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>

Button handler:

private async void Categorie_Onclick(Object sender, EventArgs args)
{
    Image cmd = sender as Image;
    string txt = TapGestureRecognizer.tag.ToString();
    await Navigation.PushAsync(new CategoriePage());
}
like image 337
N. Smeding Avatar asked Dec 08 '22 20:12

N. Smeding


1 Answers

You could abuse of StyleId, ClassId or AutomationId for this, but it's bad, so don't.

The cleanest way to do this is to define an attached BindableProperty. You can define it in the class you want.

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);
    }
}

Then you can set this Tag in Xaml

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

and get that Tag back from your event handler

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

You might wonder why this is not built into the platform. well, it's likely because with a proper Mvvm usage, this would not be required.

like image 102
Stephane Delcroix Avatar answered Jan 05 '23 04:01

Stephane Delcroix