2015-10-20 34 views
3

我想在應用程序啓動後立即將contentDialog顯示爲登錄屏幕。只有當用戶通過身份驗證時,我纔會顯示其餘的頁面,否則不會出現。Win 10上的ContentDialog.showAsync通用窗口應用程序

我不希望用戶點擊任何按鈕來加載這個內容對話框,它應該在應用程序啓動後自動出現。

在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

回答

2

首先,你只是想顯示彈出當用戶在該網頁上,這樣的代碼構造移動到OnNavigatedTo方法。當用戶界面還沒有準備好時,確實會出現錯誤,所以簡單的攻擊是await Task.Delay(1);優先,然後調用ShowPopup方法。

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

編輯:作爲@sibbl提到的,它甚至更聰明,如果你使用的代碼隱藏使用頁面加載事件。我參加了OnNavigatedTo,因爲我總是使用Prism來實現MVVM,而在ViewModel中,它是您需要實現的OnNavigatedTo方法。

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

額外注:你應該NOT use async void您ShowPopup方法,這應該只用於事件處理器。我真的鼓勵你去閱讀異步/等待,以防止'怪異'的錯誤。所以你的代碼歸結爲:

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

private Task<ContentDialogResult> ShowPopup() 
{ 
    return loginDialog.ShowAsync().AsTask(); 
} 
+0

我剛剛執行了上述所有代碼。但我仍然得到相同的錯誤。 :( – sagar

+0

我將延遲從1增加到100.現在它可以工作了,非常感謝!! – sagar

+2

更好地使用頁面的OnLoaded事件處理程序來絕對確保XAML已加載並且loginDialog存在。仍然沒有足夠的時間在一些設備上,所以要準備好崩潰...... – sibbl

相關問題