Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContentDialog.showAsync on Win 10 Universal window app

I want to show the contentDialog as a login screen as soon as the application is launched. Only if user is authenticated, i want to show rest of pages otherwise nothing should come up.

I dont want user to click any button to load this Content dialog, it should come up by itself as soon as the app is launched.

In the MainPage constructor i call the method to show the dialog.

But i get this exception "Value does not fall within the expected range." (System.ArgumentException) and the app doesnt load after that.

this is from my MainPage.xaml

 <ContentDialog x:Name="loginDialog"
                    VerticalAlignment="Stretch"
                    Title="Login"
                    PrimaryButtonText="Login"
                    SecondaryButtonText="Cancel">
                    <StackPanel>
                        <StackPanel>
                            <TextBlock Text="Username" />
                            <TextBox x:Name="Username" ></TextBox>
                        </StackPanel>
                        <StackPanel>
                            <TextBlock Text="Password" />
                            <TextBox x:Name="Password" ></TextBox>
                        </StackPanel>
                    </StackPanel>
                </ContentDialog>

Is this not possible? Can the ContentDialog be triggered only with button click? enter image description here enter image description here

like image 530
sagar Avatar asked Sep 26 '22 10:09

sagar


1 Answers

First of all, you only want to show the popup when a user is on that page, so move the code from the constructor to the OnNavigatedTo method. There's indeed an error thrown when the UI is not ready, so an easy hack is await Task.Delay(1); to give priority and then call your ShowPopup method.

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    await Task.Delay(1);
    var result = await loginDialog.ShowAsync();
}

Edit: as @sibbl mentioned, it's even wiser to use the page Loaded event if you're using code-behind. I went for OnNavigatedTo as I'm always using Prism for MVVM and in the ViewModel it's the OnNavigatedTo method you need to implement.

private async void MainPage_OnLoaded(object sender, RoutedEventArgs e)
{
    var result = await ShowPopup();
}

Extra note: you should NOT use async void for your ShowPopup method as this should only be used for eventhandlers. I really encourage you to go read up on async/await to prevent 'weird' bugs. So your code comes down to:

protected override async void OnNavigatedTo(NavigationEventArgs e)
{
    await Task.Delay(1);
    var result = await ShowPopup();
}

private Task<ContentDialogResult> ShowPopup()
{
    return loginDialog.ShowAsync().AsTask();
}
like image 64
Bart Avatar answered Sep 29 '22 07:09

Bart