Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How get x:name of element in code behind / XAML

I have some images in .xaml like below:

<Image x:Name="image1" Source="image1.png">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="OnTapGestureTap" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>

<Image x:Name="image2" Source="image2.png">
<Image.GestureRecognizers>
<TapGestureRecognizer Tapped="OnTapGestureTap" NumberOfTapsRequired="1" />
</Image.GestureRecognizers>
</Image>

when clicked, images call some action. Now in xaml.cs file I need get which image was clicked for use in switch:

    async void OnTapGestureTap(object sender, EventArgs args)
    {
        switch () //--HOW VERIFY IN SWiTCH WHICH IMAGE WAS CLICKED???
        {
            case image1:
                await Navigation.PushAsync(new Image1Page());
                break;
            case image2:
                await Navigation.PushAsync(new Image2Page());
                break;
        }
    }
like image 820
Diego Venâncio Avatar asked Oct 11 '25 17:10

Diego Venâncio


1 Answers

You could retrieve the original image name and switch on that string:

if (sender is Image image)
{
    switch (image.Source as FileImageSource).File) 
    {
        case "image1.png":
            Console.WriteLine("image1.png");
            break;
        case "image2.png":
            Console.WriteLine("image2.png");
            break;
    }
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!