Search code examples
c#xamarin.formsfloating-action-button

How to trigger floating action button OnClicked EventHandler on Xamarin Forms


I am using the NuGet Package https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android to implement a floating action button. I have already added it, but I can't get the clicked event working.

MyPage.xaml:

<fab:FloatingActionButtonView ImageName="settings_24.png"
                              ColorNormal="{StaticResource PrimaryColor}"
                              ColorPressed="{StaticResource PrimaryDarkColor}"
                              ColorRipple="{StaticResource PrimaryDarkColor}"
                              x:Name="FABaddTx"
                              AbsoluteLayout.LayoutFlags="PositionProportional"
                              AbsoluteLayout.LayoutBounds="1, 1, AutoSize, AutoSize"
                              Clicked="FAB_Clicked"/>

MyPage.xaml.cs:

private void FAB_Clicked(object sender, EventArgs e)
{
    var page = new AddTransactionPage();
    Navigation.PushAsync(page);
}

I found out that FloatingActionButtonView.Clicked is a Property and not an Event, but how does it work then? There is neither a ItemTapped or ItemSelected Event which I could use.

I have already looked throught the sample code provided on the GitHub repo, sadly there is only Xamarin.Android code, while I would need Xamarin.Forms.


Solution

  • According to this Xamarin.Forms example from the source repository it is an action delegate property.

    /// <summary>
    /// Action to call when clicked
    /// </summary>
    public Action<object, EventArgs> Clicked { get; set; }
    

    Source

    You can set the delegate within the constructor of the Page.

    However, given that it is not an actual event handler and just a void method, it would be ill advised to make it an async void method if you want to perform async operations safely.

    Reference Async/Await - Best Practices in Asynchronous Programming

    Instead, create an event and async event handler so that async operations can be awaited

    MyPage.xaml.cs:

    public MyPage() {
        //Subscribing to our event here
        FabClicked += OnFabClicked;
        //FABaddT is already defined in the XAML so just setting the delegate here
        FABaddT.Clicked = (sender, args) => {
            //Raising the event here and passing sender and event arguments on
            FabClicked(sender, args);
        };
    }
    
    private event EventHandler FabClicked = delegate { };
    
    private async void OnFabClicked(object sender, EventArgs args) {
        var page = new AddTransactionPage();
        await Navigation.PushAsync(page);
    }