Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameter to command

I have Xamarin Forms solution and on one page there is list with images. When image is clicked, I would like to trigger procedure witch has image path as parameter. In xaml I define image with:

<Image Source="{Binding ImagePath}"
        WidthRequest="30" HeightRequest="30"
        HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand" >
  <Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding ImagePath}" />
  </Image.GestureRecognizers>
</Image>

and TapImageCommand is defined in view model's constructor as:

TapImageCommand = new Command<string>(ImagePath =>
{
    OnImageTapped(ImagePath);
});

and TapImageCommand is defined with:

public ICommand TapImageCommand { get; set; }

Problem is OnImageTapped is never triggered. What am I doing wrong?

like image 663
Uros Avatar asked Sep 16 '25 12:09

Uros


1 Answers

The problem here is that you think you are binding the ImagePath of the object behind the list, but you are not. Look at the Command you are binding, this is part of the PageModel, not the object in the list, so neither is the CommandParameter.

Therefore, ImagePath is probably null, and it does not match the signature you have for the Command which expects a string.

In this particular case it is probably easiest to supply the whole object as a parameter and get out the property yourself. I will assume the object in the list is of type Foo, then edit your code like underneath.

In your view, edit the TapGestureRecognizer to this:

TapGestureRecognizer Command="{Binding TapImageCommand}" CommandParameter="{Binding .}" />

The dot points to itself, in this case the specific instance of Foo in your list. Then edit the Command like this:

TapImageCommand = new Command<Foo>(fooObject =>
{
    OnImageTapped(fooObject);
});

Now in your OnImageTapped method you can extract the ImagePath property.

like image 167
Gerald Versluis Avatar answered Sep 18 '25 09:09

Gerald Versluis