我們開發的應用在Win8 介面中會以磁貼形式展現,預設情況下磁貼會顯示應用表徵圖,即項目工程中的Logo.png圖片檔案。開發人員可按應用的需要使用通知的方式將文字或圖片資訊推送到磁貼,從而對磁貼中顯示的內容進行更換。
對於磁貼通知推送主要用到API 是Windows.UI.Notifications,API 中提供了很多磁貼顯示模版TileTemplateType,模版的結構是通過XML 描述的。其實我們需要做的就是編輯模版中的內容,然後將它推送到磁貼。有些童鞋可能發現下面代碼中定義了兩個模版:TileWideImageAndText01 和TileSquareText04。這是由於Win8 應用有大小兩種尺寸的磁貼,在應用推播通知時無法知道當前磁貼的大小,如果推送的模版內容與磁貼尺寸不符,在顯示方面可能會產生問題,所以官方建議將兩種尺寸得模版全部定義好,這樣無論磁貼處於哪種尺寸都不會發生顯示問題。
<tile> <visual> <binding template="TileWideImageAndText01"> <image src="ms-appx:///Assets/Wide.png"/> <text>This is a wide tile notification!</text> </binding> <binding template="TileSquareText04"> <text>This is a square tile notification!</text> </binding> </visual></tile>
接下來我們需要做的就是編輯模版內容(如下代碼),先用TileUpdateManager 類的GetTemplateContent 方法定義大尺寸磁貼模版,樣本中TileWideImageAndText01 是帶有圖片和文字的大尺寸模版,TileTemplateType 枚舉還包含其他類型的模版,開發人員可自行選取使用。後續使用標準BOM 編輯模版的<text> 和<image> 標籤設定相應的數值和屬性。
同樣,編輯完小尺寸磁貼後,將其載入到大尺寸模版<visual>(如上XML)。通過TileNotification 建立一個磁貼通知,可使用ExpirationTime 設定磁貼通知消失時間。最後,使用TileUpdateManager.CreateTileUpdaterForApplication().Update() 推播通知,可使用Clear() 清除磁貼通知。
// For wide tileXmlDocument wideTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWideImageAndText01);XmlNodeList wdTxtAttribute = wideTile.GetElementsByTagName("text");XmlNodeList wdImgAttribute = wideTile.GetElementsByTagName("image");((XmlElement)wdImgAttribute[0]).SetAttribute("src", "ms-appx:///Assets/Wide.png");wdTxtAttribute[0].InnerText = "This is a wide tile notification!";// For square tileXmlDocument sqTile = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText04);XmlNodeList sqTxtAttribute = sqTile.GetElementsByTagName("text");sqTxtAttribute[0].InnerText = "This is a square tile notification!";IXmlNode node = wideTile.ImportNode(sqTile.GetElementsByTagName("binding").Item(0), true);wideTile.GetElementsByTagName("visual").Item(0).AppendChild(node);TileNotification tileNotification = new TileNotification(wideTile);tileNotification.ExpirationTime = DateTimeOffset.UtcNow.AddSeconds(10);TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
圖示
源碼下載
http://sdrv.ms/WhVSLU