Search code examples
xamarin.formsdata-bindingviewmodelimagebutton

ImageButton not firing Command binding in Xamarin Forms


I have an ImageButton that is not firing Command binding command using VMMV architecture. First all other bindings are working properly in the view.

Here is button:

<ImageButton Command="{Binding SelectedItemCommand}" Source="{Binding Logo}" Grid.Row="0" Grid.Column="1" HeightRequest="150" WidthRequest="150" HorizontalOptions="CenterAndExpand" VerticalOptions="EndAndExpand"></ImageButton>

and in ViewModel:

public ICommand SelectedItemCommand => new Command(GetSelectedItem);

When I click the image nothing happens. I've even tried to bind to Pressed parameter but from everything I have read only the Command parameter should be used in a binding scenario. Putting a breakpoint on the function GetSelectedItem never gets reached.

What am I doing wrong here?

Sorry been away for a few days. So nothing was working on the suggestions even though they really should be clicking wouldn't fire command. Anyway I managed to get it to fire now using an eventhandler like so:

SelectedItemCommand = new Command<string>(param => OnItemSelected(param));

public void OnItemSelected(string img1_2)
{
  PressedEventHandler?.Invoke(this, EventArgs.Empty);
}

The param captures the CommandParameter so I know which image to the question was clicked "img1" "img2" to do something specific. So my function now accepts a sender object and empty eventarg. I would like to instead pass img1_2 value but that doesn't appear to be possible as of now. What is cusrious is the sender object contains all the properties and values from the images (like an array of all my properties) but I cannot seem to get at them. Attempted this:

string str = Item1Image.ToString(); // property in sender and viewmodel

But this returns a null value and not value listed in the sender object value?

Any additional thoughts?

TIA! Rick...


Solution

  • public ICommand SelectedItemCommand {get; private set;}
    
    ...
    
    public YourViewModel(){
       ...
       SelectedItemCommand = new Command(GetSelectedItem);
       ...
    }
    ...
    

    Or

    public ICommand SelectedItemCommand{
       get
       {
          return new Command(() => {
               //Do something
          });
       }
    }