# 使用Toast通知示例
前面我們使用了MessageDialog來作為彈窗,這里來介紹一個更加高大上的Toast通知。
Toast通知本質上動力是由XML來提供的,一開始我還不相信不知道XML原來有這么大的威力。現在就來看看和Toast相關的知識。
1)實例化ToastNotification類。
~~~
ToastNotification toast1 = new ToastNotification(xdoc);
~~~
2)使用ToastNotificationManager來管理Toast通知,包括添加、展示、移除、獲取通知等等。
~~~
ToastNotificationManager.CreateToastNotifier().Show(toast1);
~~~
3)在第一步中的xdoc就是一段XML數據,它從何而來呢?
~~~
XmlDocument xdoc = new XmlDocument();
~~~
4)上一步代碼實例化了一個XML,但是它沒有數據呀,數據從哪來呢?
~~~
xdoc.LoadXml(txtXML.Text);
~~~
5)這段代碼就將一段Text導入了XML中。而Text數據有很多種獲取方式。在下文中自然會提到。
Toast的XML模板有許多,我們可以直接來獲取它們。用枚舉和強大的var即可。
~~~
var items = Enum.GetNames(typeof(ToastTemplateType));
~~~
那么就正式開工了,因為重復的屬性太多了我就大概設置了2個Style資源。
~~~
<Page.Resources>
<Style TargetType="TextBlock" x:Key="StyleHeaderTextBlock">
<Setter Property="FontSize" Value="40"/>
<Setter Property="FontFamily" Value="華文琥珀"/>
<Setter Property="Foreground" Value="HotPink"/>
<Setter Property="Margin" Value="12"/>
</Style>
<Style TargetType="Button" x:Key="StyleToastButton">
<Setter Property="Width" Value="180"/>
<Setter Property="Height" Value="50"/>
<Setter Property="Background" Value="Aqua"/>
<Setter Property="FontSize" Value="21"/>
<Setter Property="Margin" Value="12"/>
<Setter Property="Content" Value="顯示Toast通知" />
</Style>
</Page.Resources>
~~~
下面是第一部分用于生成Toast通知。
~~~
<StackPanel Orientation="Vertical" Grid.Column="0" Margin="12">
<TextBlock Text="生成Toast通知" Style="{StaticResource StyleHeaderTextBlock}"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<TextBlock FontSize="24" Foreground="Wheat" Text="請選擇一個模板:" VerticalAlignment="Center"/>
<ComboBox Name="comboBoxToast" Foreground="Green" Width="275"
SelectionChanged="comboBoxToast_SelectionChanged"/>
</StackPanel>
<TextBox Foreground="Green" x:Name="txtXML" HorizontalAlignment="Left" Width="500" Height="400" Header="模板XML:" TextWrapping="Wrap" FontSize="24"/>
<Button Name="btnShowToast1" Click="btnShowToast1_Click" Style="{StaticResource StyleToastButton}"/>
</StackPanel>
~~~
后臺代碼也蠻容易的,利用上面講的就好了。
~~~
public MainPage()
{
this.InitializeComponent();
var items = Enum.GetNames(typeof(ToastTemplateType));
this.comboBoxToast.ItemsSource = items;
}
private void comboBoxToast_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string tempt = ((ComboBox)sender).SelectedItem as string;
if (!string.IsNullOrEmpty(tempt))
{
ToastTemplateType template = (ToastTemplateType)Enum.Parse(typeof(ToastTemplateType), tempt);
XmlDocument xdoc = ToastNotificationManager.GetTemplateContent(template);
txtXML.Text = xdoc.GetXml();
}
}
private void btnShowToast1_Click(object sender, RoutedEventArgs e)
{
if (txtXML.Text == "")
return;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(txtXML.Text);
ToastNotification toast1 = new ToastNotification(xdoc); ToastNotificationManager.CreateToastNotifier().Show(toast1);
}
~~~
模板是這樣用的……


在src中填入圖片的路徑也可以在Toast中顯示圖像哦,趕緊試試吧……
接下來是第二段啦,和前面的很是類似……
~~~
<StackPanel Orientation="Vertical" Grid.Column="1">
<TextBlock Text="更改Toast通知的提示音" Style="{StaticResource StyleHeaderTextBlock}"/>
<TextBlock Margin="12" Text="請輸入Toast消息內容:" FontSize="24"/>
<TextBox Margin="12" Height="50" x:Name="txtMesaage"/>
<TextBlock Margin="12" FontSize="24" Text="請選擇一種提示聲音:"/>
<ComboBox Margin="12" Height="50" x:Name="comboBoxAudio" Width="400" HorizontalAlignment="Left">
<ComboBoxItem IsSelected="True">ms-winsoundevent:Notification.Default</ComboBoxItem>
<ComboBoxItem>ms-winsoundevent:Notification.IM</ComboBoxItem>
<ComboBoxItem>ms-winsoundevent:Notification.Mail</ComboBoxItem>
<ComboBoxItem>ms-winsoundevent:Notification.Reminder</ComboBoxItem>
<ComboBoxItem>ms-winsoundevent:Notification.Looping.Alarm</ComboBoxItem>
<ComboBoxItem>ms-winsoundevent:Notification.Looping.Call</ComboBoxItem>
</ComboBox>
<StackPanel Orientation="Horizontal">
<CheckBox x:Name="checkBoxLoop" Margin="12" Content="循環播放"/>
<CheckBox x:Name="checkBoxSilent" Margin="12" Content="靜音"/>
</StackPanel>
<Button Name="btnShowToast2" Click="btnShowToast2_Click" Style="{StaticResource StyleToastButton}"/>
</StackPanel>
~~~
上面代碼中的“ms-winsoundevent:Notification.Default”都是填到src中的用于設置聲音,還可以在loop、silent中設置是否循環以及是否靜音,那到底該怎么用呢?應該將這些屬性全部都填入到XML中。
~~~
xmlContent = string.Format(
"<toast duration='{0}'>" +
"<visual>" +
"<binding template='ToastText01'>" +
"<text id='1'>{1}</text>" +
"</binding>" +
"</visual>" +
"<audio src='{2}' loop='{3}' silent='{4}'/>" +
"</toast>",
toastDuration, msg, audioSrc, isLoop, isSilent
);
~~~
上面用的xmlContent也要先定義出來,一開始設置為Empty就好。
~~~
string xmlContent = string.Empty;
~~~
isLoop和isSilent屬性都可以借助于三目運算符在CheckBox中獲取來。
~~~
string isLoop = checkBoxLoop.IsChecked == true ? "true" : "false";
string audioSrc = (comboBoxAudio.SelectedItem as ComboBoxItem).Content.ToString();
string toastDuration = checkBoxLoop.IsChecked == true ? "long" : "short";
string isSilent = checkBoxSilent.IsChecked == true ? "true" : "false";
~~~
當然,考慮得更加周到些,用戶可以在還沒有輸入通知內容就點了顯示Toast通知按鈕,對此用三目運算符也是極好的選擇。
~~~
string msg = txtMesaage.Text == "" ? "你還沒有輸入Toast通知的內容呢……" : txtMesaage.Text;
~~~
這些準備工作都寫好了以后呢就該設置Toast通知了,和上面的Toast1類似哦,大家試試。
可是這些通知都沒有時間性可言,因為有時候我們需要定在一個時間來執行Toast通知。這自然也是可以實現的。
先作如下界面設計。
~~~
<StackPanel Orientation="Vertical" Grid.Column="2">
<TextBlock Text="計劃時間顯示Toast通知" Style="{StaticResource StyleHeaderTextBlock}"/>
<StackPanel Orientation="Horizontal" Height="60">
<TextBlock FontSize="28" Text="計劃在" VerticalAlignment="Center"/>
<TextBox Name="tBoxTime" FontSize="28" Width="60" Height="45" VerticalAlignment="Center"/>
<TextBlock FontSize="28" Text="秒后顯示Toast通知" VerticalAlignment="Center"/>
</StackPanel>
<Button Name="btnShowToast3" Click="btnShowToast3_Click" Style="{StaticResource StyleToastButton}"/>
</StackPanel>
~~~
后臺代碼如下。
~~~
private async void btnShowToast3_Click(object sender, RoutedEventArgs e)
{
int toastTime;
try
{
toastTime = int.Parse(tBoxTime.Text.ToString());
XmlDocument xdoc = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
var txtnodes = xdoc.GetElementsByTagName("text");
txtnodes[0].InnerText = "你好,這是一條定時為"+toastTime.ToString()+ "秒的Toast消息。";
ScheduledToastNotification toast3 = new ScheduledToastNotification(xdoc, DateTimeOffset.Now.AddSeconds(toastTime)); ToastNotificationManager.CreateToastNotifier().AddToSchedule(toast3);
}
catch (Exception ex)
{
Windows.UI.Popups.MessageDialog messageDialog =
new Windows.UI.Popups.MessageDialog(ex.Message);
await messageDialog.ShowAsync();
}
}
~~~
在這個小程序中因為側重于講解定時而非Toast的通知樣式,因此就選用了比較簡單的ToastText01模板。而后找出Text節點,并向該節點寫入內容。最后就是創建Toast通知了。
~~~
ScheduledToastNotification toast3 = new ScheduledToastNotification(xdoc, DateTimeOffset.Now.AddSeconds(toastTime));
~~~
同樣為了防止用戶沒有在TextBox中輸入時間或輸入了錯誤格式的時間比如“5秒”而做了try、catch異常檢測。當然了,在實際產品中,這里可就要做得更加完美了,時間用TextBox來輸入并不是一件好事,而應用我們前面介紹的TimePicker。
給這3段程序來張全家福吧~

# 使用動態磁貼示例
動態磁貼是什么,相信大家用了這么久的Windows 8/8.1/10早就非常了解了吧。
像什么小磁貼、中磁貼、寬磁貼、大磁貼,還有這里的應用商店Logo等,大家在下面根據不同的分辨率選擇合適的圖片就好啦。

下面來做一個更新磁貼頁面的功能,這是頁面XML部分。
~~~
<StackPanel Margin="12">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="28" Text="選擇模板:" VerticalAlignment="Center"/>
<ComboBox x:Name="comboBoxTile" Width="400" SelectionChanged="comboBoxTile_SelectionChanged"/>
</StackPanel>
<TextBox x:Name="textBoxXML" TextWrapping="Wrap" FontSize="22" Header="XML文檔" Width="420" Height="320" HorizontalAlignment="Left" Margin="12"/>
<Button Name="btnTile" Content="更新磁貼" Click="btnTile_Click" Style="{StaticResource StyleToastButton}"/>
</StackPanel>
~~~
在后臺代碼的Main函數中,獲取TileTemplateType枚舉并綁定到ComboBox上。
~~~
var itemsTile = Enum.GetNames(typeof(TileTemplateType));
this.comboBoxTile.ItemsSource = itemsTile;
~~~
下面的代碼和前面的Toast真的非常類似,所以我才把這兩節連在一起來寫了。Button按鈕的Click事件中,和之前一樣建一個XML,然后加載到TileNotification類的實例中。最后就是TileUpdateManager類,也就是磁貼更新。
~~~
private void btnTile_Click(object sender, RoutedEventArgs e)
{
if (this.textBoxXML.Text == "")
return;
XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(this.textBoxXML.Text);
TileNotification tileNotifi = new TileNotification(xdoc);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotifi);
}
private void comboBoxTile_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
TileTemplateType tileTemplate = (TileTemplateType)Enum.Parse(typeof(TileTemplateType),
this.comboBoxTile.SelectedItem as string);
XmlDocument xdoc = TileUpdateManager.GetTemplateContent(tileTemplate);
this.textBoxXML.Text = xdoc.GetXml();
}
~~~
當然了,如果你的APP不滿足于一個磁貼,你也可以創建第二個磁貼喲!
依舊和Toast通知的XML類似,它也有好多屬性的……
Arguments:使用該字符串參數在通過次要磁貼啟動應用程序時會傳遞給Application類的OnLaunched方法,這樣一來應用程序就可以根據傳入的參數來執行特定的操作。
BackgroundColor:設置磁貼的背景色。
DisplayName和ShortName:設置顯示在磁貼上的文本。
Logo等:設置磁貼的圖標,用Uri。
ForegroundText:磁貼上文本的顏色,可用的選項有深色、淺色等。
TileID:設置磁貼的唯一標識ID,創建新磁貼前用SecondaryTile.Exists判斷是否已經存在。
在添加第二磁貼的Button的Click事件中:
~~~
private async void btnCreateTile(object sender, RoutedEventArgs e)
{
if(SecondaryTile.Exists(textTileID.Text))
{
textBlockMsg.Text="該ID磁貼已經存在";
return ;
}
Uri uriImg=new Uri("ms-appx:///Assests/uriImg.png");
……
……
// 創建第二磁貼
SecondaryTile secTile=new SecondaryTile();
this.Tag=secTile;
secTile.DisplayName=textBlockDisplayName.Text;
secTile.TileID=textBlockID.Text;
secTile.Arguments="second"; // 在后面有用到
// 設置圖標
secTile.VisualElements.BackgroundColor=Windows.UI.Colors.Gold;
……
……
bool r=await secTile.RequestCreateAsync();
textBlockMsg.Text=r == true ?"磁貼創建成功啦.":"磁貼創建失敗了哎."; // 返回測試結果
~~~
如果希望點擊第二磁貼導航到特定的頁面,就需要重寫該頁面的OnNavigatedTo方法。
~~~
preteced async override void OnNavigatedTo(NavigationEventArgs e)
{
if(e.Parameter is Windows.ApplicationModel.Activation.LaunchActivatedEventArgs)
{
var arg=e.Parameter as Windows.ApplicationModel.Activation.LaunchActivateEventArgs;
……
}
}
if(rootFrame.Content==null)
{
if(e.Arguments=="second")
rootFrame.Navigate(typeof(OtherPage),e);
else
rootFrame.Navigate(typeof(MainPage));
}
~~~
這里的參數”second”就是上面設置那個Arguments哦,它的作用就在于這里呢。