Search code examples
c#xamarinxamarin.formsdata-binding

Xamarin command data binding works if => operator used but does not work if = operator used


I have simple Xamarin forms(5.0.0.2012) application. It contains a XAML page and a corresponding view model.

I have the following SearchBar element in the XAML file:

    <SearchBar x:Name="searchBar"
               HorizontalOptions="Fill"
               VerticalOptions="CenterAndExpand"
               Placeholder="Search vacancies..."
               SearchCommand="{Binding PerformSearchCommand}" 
               SearchCommandParameter="{Binding Text, Source={x:Reference searchBar}}"/>

I have the following public Command property and static method in the view model:

public class SearchViewModel : INotifyPropertyChanged
{
    public ICommand PerformSearchCommand => new Command(PerformSearch);

    public event PropertyChangedEventHandler PropertyChanged;

    private static void PerformSearch()
    {
        var i = 10;
        i++;
    }

When the search icon is clicked in the SearchBar. The PerformSearch() method is executed as expected. However, if I change the code to the following, the PerformSearch() method is no longer called.

public class SearchViewModel : INotifyPropertyChanged
{
    public ICommand PerformSearchCommand = new Command(PerformSearch);

    public event PropertyChangedEventHandler PropertyChanged;

    private static void PerformSearch()
    {
        var i = 10;
        i++;
    }

I need to be able to use '=' approach to initialise the command in the constructor to pass in a non static method to execute. I have tested this issue on an android emulator. Is this a Xamarin bug?


Solution

  • Because your Command needs to be a property in order to be able to bind it. The first line is a property because:

    public ICommand PerformSearchCommand => new Command(PerformSearch);
    

    is equivalent to

    public ICommand PerformSearchCommand { get { return new Command(PerformSearch); }
    

    The second one is a field not a property

     public ICommand PerformSearchCommand = new Command(PerformSearch);
    

    Related questions

    What is the => assignment in C# in a property signature

    What does "=>" operator mean in a property in C#?

    What is the difference between a field and a property?

    Related documentations

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-operator

    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/