Search code examples
xamarin.formsdisplayalert

Xamarin Forms: DisplayAlert background tap firing the cancel event


I am using a DisplayAlert like below in my project.

var answer = await DisplayAlert("Alert", "You are invited to join a group, would you like to accept it or not?", "Accept", "Reject");
if (answer)
{
    //accept invitation
}
else
{
    //reject invitation
}

Accept and Reject options are working fine. My problem is Reject option is executing when tapping on the background or device back arrow. Is it has a simple solution other than implementing Rg.Plugins.Popup?


Solution

  • I had a similar request once, and I quickly "solved it" with a workaround like this (using DisplayActionSheet):

    bool isActionSelected = false;
    while(!isActionSelected)
    {
        string action = await DisplayActionSheet ("You are invited to join a group, would you like to accept it or not?", null, null, "Accept", "Reject");
        if (action == "Accept")
        {
            isActionSelected = true;
            //do stuff         
        }
        else if (action == "Reject")
        {
            isActionSelected = true;
            //do stuff         
        }
        else
        {
            isActionSelected = false;
        }
    }
    

    This is not suggested, unless you are in a hurry.

    So, I would suggest you creating a custom popupView, something like this

                <ContentView x:Name="popupView" BackgroundColor="#C0808080" Padding="10, 0" IsVisible="false" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" AbsoluteLayout.LayoutFlags="All">
                    <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
                        <StackLayout Orientation="Vertical" HeightRequest="150" WidthRequest="200" BackgroundColor="White">                        
                            <Label x:Name="myLabel" TextColor="Black" Text="You are invited to join a group, would you like to accept it or not?" />
                            <Button Text="Accept" TextTransform="None" Clicked="AcceptClicked" />
                            <Button Text="Reject" TextTransform="None" Clicked="RejectClicked" />
                        </StackLayout>
                    </StackLayout>
                </ContentView>
    

    then in .cs

    popupView.IsVisible = true;
    

    when you want this to appear.