Logout Display alert xamarin.forms

2020-03-30 02:15发布

I've been trying to allow a user to confirm logout by using DisplayAlert. If they click "No" it should remain in their profile page else they should be redirected back to the login page. I haven't managed to get this done, if I click Yes or No, both options remain in the profile page

public async void LogoutBtn(object sender, EventArgs e)
{
    var answer = await DisplayAlert("Exit", "Do you wan't to exit the App?", "Yes", "No");
    if(answer.Equals("Yes"))
    {
        Settings.FirstName = string.Empty;
        Settings.LastName = string.Empty;
        Settings.Email = string.Empty;
        await Navigation.PushAsync(new MainPage());
    }
    else
    {
        App.Current.MainPage = new Profile();
    }
}

2条回答
迷人小祖宗
2楼-- · 2020-03-30 02:26

DisplayAlert returns a boolean (true / false):

var answer = await DisplayAlert("Exit", "Do you wan't to exit the App?", "Yes", "No");
if (answer)
{
    // User choose Yes
}
else
{
    // User choose No
}
查看更多
够拽才男人
3楼-- · 2020-03-30 02:37

As SushiHangover point out DisplayAlert returns a bool. You should replace it with DisplayActionSheet or stay with it and correct the if.

Your else clause seems to be incorrect.
If the user choose No you should do nothing. Why do you assign a new Profile to the MainPage?

Beside that, it seems that you have problems with navigation in general. Looking at your code, logout will push a page on a top of the executing page. Seems a bit weird. I would recommend to get familiar wit the Navigation topic firs of all:
Official doc
There is a free course on Xamarin University on Navigation

查看更多
登录 后发表回答