Search code examples
c#.netmauimaui-community-toolkit

.NET 8 MAUI Button Binding with CommunityToolkit.MVVM


This is the method I wish to trigger in my code behind using the ComunityToolkit.MVVMpackage. My ViewModel

[RelayCommand]
public async Task CreateBookingCommand()
{
    await Shell.Current.GoToAsync(nameof(BookingCreate)); 
}

my View

<Button Text="Place Request" Grid.Row="1" Padding="10" CommandParameter="{Binding .}"
        Command="{Binding CreateBookingCommand}"/>

and this is the error I get when I run in debug mode.

Severity    Code    Description Project File    Line    Suppression State Error (active)    XFC0045 Binding: Property "CreateBookingCommand" 

From my understanding the nugget package is supposed to auto generate a property trigger but that doesn't seem to be happening. I'm using .NET 8 and version 8.2.2 of the CommunityToolkit.MVVM package


Solution

  • According to the RelayCommand attribute, when you RelayCommand attribute on a method, such as CreateBooking, it will generate a command like this:

    private RelayCommand? createBookingCommand;
    
    public IRelayCommand CreateBookingCommand => createBookingCommand ??= new RelayCommand(CreateBooking);
    

    So, you only need to remove the Command suffix for the method name and it works,

    [RelayCommand]
    public async Task CreateBooking()
    {
        ......
    

    or since it's asynchronous methods, add a Async suffix seems better, also works

    [RelayCommand]
    public async Task CreateBookingAsync()
    {
        ......
    

    For more info, please refer to RelayCommand attribute