Search code examples
c#xamlmaui

MAUI - Buttons interfere with each other


I have a xaml file with 2 basic buttons: button_1 and Button_2

The problem, is that the first button is responsive, but Button_2 is not.

However, if I move Button_2 above Button_1 in the xaml file, then Button_2 becomes responsive while button_1 is not anymore.

Any idea what I am doing wrong here?

I havent added the VM,as 2 methods are very distinct from each other so I don't think it this matters. SOmething tells me its coming from the xaml file.

I tried to wrap them in <StackLayout>, just in case the behaviour might change but no.

xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="App._Views.FolderName.View"


            <!-- BUtton 1-->
            <StackLayout/>

                    <Button 
                         Command="{Binding Button1Command}"
                         CommandParameter="{Binding .}" />

            <!-- BUtton 2-->

                    <Button
                     Command="{Binding Button2Command}"
                     CommandParameter="{Binding .}" />

            </StackLayout>
</ContentPage>

ViewModel - using breapoint, Button2() is not accessed.

      public partial class VM: ObservableObject, IQueryAttributable
      {
    
    
            [RelayCommand]
            private async void Button1()
            {
                Console.WriteLine("Button1 is accessed");
    
            }
    
    
            [RelayCommand]
            private async void Button2()
            {
                Debug.WriteLine("Button 2 is clicked")
}

   }

Solution

  • It will work if you give the method the correct signature so it can generate the RelayCommand.

    Avoid async void and use async Task instead, or in this case, you don't run async code, so just use a void method.

    [RelayCommand]
    private void Button1()
    {
        Console.WriteLine("Button1 is accessed");
    } 
    

    alternative:

    [RelayCommand]
    private async Task Button1Async()
    {
        Console.WriteLine("Button1 is accessed");
    }