M. Chris
M. Chris

Reputation: 171

Xamarin Command not firing on Button Click

I've made a Xamarin application for testing purposes and for some reason, the button that I've added won't fire the command. I've tried setting the context from code-behind and xaml as well, but it still doesn't work.

XAML Code:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:implementation="clr-namespace:RxposTestApp.Implementation;assembly=RxposTestApp"
             x:Class="RxposTestApp.Page">
    <ContentPage.BindingContext>
        <implementation:BaseCommandHandler/>
    </ContentPage.BindingContext>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            <Button Text="CLIK MIE" Command="BaseCommand"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

BaseCommandHandler class:

public class BaseCommandHandler : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand BaseCommand { get; set; }

    public BaseCommandHandler()
    {
        BaseCommand = new Command(HandleCommand);
    }



    public void HandleCommand()
    {
       //should fire this method
    }
}

Upvotes: 1

Views: 5545

Answers (2)

Neil
Neil

Reputation: 637

So the problem is

<Button Text="CLIK MIE" Command="BaseCommand"/>

Let's take a step back and talk about the binding.

<Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>

You will notice {Binding ...}, that is telling the XAML engine to look for a public property on the binding context. In this case, we want to Look for a public property named "BaseCommand". Binding provides quite a few things. One of those things being listening for property change notification.

Next question is how are we notifying the view that the command can be executed? or it can't currently be executed? or BaseCommand property is set to an ICommand instance instead of being null?

I typically prefer to use private fields to back public properties.

private ICommand _baseCommand;
Public ICommand BaseCommand
{
    get
       {
           return this._baseCommand;
       }
    set
       {
           this._baseCommand = value;
           // Notification for the view. 
       }
}

this way you can raise notification however you prefer and it will always be raised when the value of BaseCommand changes.

Upvotes: 3

Woj
Woj

Reputation: 833

<Button Text="CLIK MIE" Command="{Binding BaseCommand}"/>

You are using MVVM, hence you need to bind your properties from ViewModel to your View.

Upvotes: 1

Related Questions