在以前Silverlight、WPF中的快顯視窗提示中是MessageBox類中進行顯示的,現在Windows 8中使用 Windows.UI.Popups命名空間下的MessageDialog類代替MessageBox。
MessageDialog類有以下常用方法 和屬性:
ShowAsync():非同步彈出訊息框.
Commands:添加命令,在彈出框介面上同步添加相應的按 鈕.
DefaultCommandIndex:設定預設按鈕的索引,按ENTER鍵將啟用該索引對應的命令按鈕
CancelCommandIndex:設定取消退出按鈕的索引,按ESC鍵將啟用該索引對應的命令按鈕
Title: 彈出訊息框的標題
async:用於方法申明時,此關鍵字是告訴編譯器在這個方法體內可能會有await關鍵 字。
await:用於非同步作業時的類比同步等待,聲明有此關鍵字的非同步作業需等待非同步作業完成之後才 繼續往下運行,但是不會阻塞UI線程。
注意:使用await關鍵字的方法體,必須使用async聲明方法
現在我們通過一個執行個體來看MessageDialog、async、await:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}"> <Button Content="First Msg" HorizontalAlignment="Left" Margin="430,196,0,0" VerticalAlignment="Top" Height="51" Width="114" Click="First_Click"/> <Button Content="Secend Msg" HorizontalAlignment="Left" Margin="606,196,0,0" VerticalAlignment="Top" Height="51" Width="114" Click="Secend_Click"/> <Button Content="Third Msg" HorizontalAlignment="Left" Margin="788,196,0,0" VerticalAlignment="Top" Height="51" Width="114" Click="Third_Click"/> <Button Content="Fourth Msg" HorizontalAlignment="Left" Margin="975,196,0,0" VerticalAlignment="Top" Height="51" Width="114" Click="Fourth_Click"/> <TextBlock HorizontalAlignment="Left" Name="tbText" Margin="573,160,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="31" Width="565" FontSize="16"/> </Grid>
一:最簡單的MessageDialog
private async void First_Click(object sender, RoutedEventArgs e) { MessageDialog msg = new MessageDialog("Hello World!這是第一個提示."); msg.Title = "提示1"; var msginfo = await msg.ShowAsync(); }
二:自訂命令集的訊息框
private async void Secend_Click(object sender, RoutedEventArgs e) { MessageDialog msg1 = new MessageDialog("Hello World!這是第二個提示."); msg1.Title = "提示2"; msg1.Commands.Add(new UICommand("確定", command => { this.tbText.Text = "你點擊了確定按鈕,第二組提示"; })); msg1.Commands.Add(new UICommand("取消", command => { this.tbText.Text = "你點擊了取消按鈕,第二組提示"; })); var msg1info = await msg1.ShowAsync(); }
三:使用await類比同步方式得到當前使用命令ID運行響應的程式碼片段
private async void Third_Click(object sender, RoutedEventArgs e) { MessageDialog msg1 = new MessageDialog("Hello World!這是第三個提示."); msg1.Title = "提示3"; msg1.Commands.Add(new UICommand("確定", null, 0)); msg1.Commands.Add(new UICommand("取消", null, 1)); msg1.DefaultCommandIndex = 0; msg1.CancelCommandIndex = 1; var msg1info = await msg1.ShowAsync(); switch (Convert.ToInt32(msg1info.Id)) { case 0 : this.tbText.Text = "你點擊了確定按鈕,第三組提示";break; case 1 : this.tbText.Text = "你點擊了取消按鈕,第三組提示";break; default: break; } }