Win 10 Universal窗口应用程序上的ContentDialog.showAsync

时间:2015-10-20 06:57:33

标签: c# xaml win-universal-app uwp

我想在启动应用程序后立即将contentDialog显示为登录屏幕。只有在用户通过身份验证后,我才会显示其余页面,否则不会出现任何问题。

我不希望用户点击任何按钮来加载此内容对话框,只要应用程序启动它就会自动出现。

在MainPage构造函数中,我调用方法来显示对话框。

但我得到了这个例外"价值不在预期的范围内。" (System.ArgumentException),然后应用程序没有加载。

这是来自我的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>

这不可能吗?只有点击按钮才能触发ContentDialog? enter image description here enter image description here

1 个答案:

答案 0 :(得分:4)

首先,您只想在用户在该页面上时显示弹出窗口,因此将代码从构造函数移动到OnNavigatedTo方法。当UI未准备好时,确实会抛出一个错误,所以一个简单的黑客是await Task.Delay(1);优先,然后调用你的ShowPopup方法。

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

编辑:正如@sibbl所提到的,如果你使用代码隐藏,那么使用页面Loaded事件会更明智。我去OnNavigatedTo,因为我总是使用Prism用于MVVM,而在ViewModel中,它是你需要实现的OnNavigatedTo方法。

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

额外注意:对于ShowPopup方法,您应该NOT use async void,因为这只应该用于事件处理程序。我真的鼓励你去async / await上阅读,以防止'怪异'的错误。所以你的代码归结为:

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

private Task<ContentDialogResult> ShowPopup()
{
    return loginDialog.ShowAsync().AsTask();
}
相关问题