Windows 8 Live Tiles and LINQ to XML by ThinqLinq

Windows 8 Live Tiles and LINQ to XML

When I started working with Windows 8 Metro development, I was disappointed to see that the native WinRT API’s relied on the older XmlDocument and XMLDom rather than the newer subset of XDocument/XElement and LINQ to XML. I suppose this was necessary because the older version was more natural for C++ and JavaScript options for Metro applications. If you’re like me and want to use LINQ to XML to work with XML in WinRT, all you need to do is pass the XML strings back and forth between your C#/VB code and the native WinRT methods.

Let’s consider the case of custom Tile Notifications. In order to set one, you first get the XML template from the TileUpdateManager. This returns an XmlDocument object with an XML template looking like this:

<tile>
  <visual>
    <binding template="TileWidePeekImage01">
      <text id="1"></text>
     </binding>
  </visual>
</tile>
In order to set the text, we need to locate the “text” element with the attribute id of 1 and set the value. While we could create the Xml from scratch, It might be safer to just set the node’s value and retain the rest of the XML. If you’ve been following my blog for any time, I find the LINQ to XML API’s to be much easier to use than the older XmlDom. Luckily, moving back and forth from XmlDom and XDocument is as simple as calling Parse on the XDocument passing in the .GetXml method of the XmlDocument. To push our changed XDocument back into the XmlDocument, we call LoadXml passing the String representation of the XDocument using ToString. Here’s the code to grab the TileSquareText04 template and set the text value to “Text Line 1”.
Dim tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareText04)

' Transition to XDocument
Dim xTile = XDocument.Parse(tileXml.GetXml())
' Manipulate with LINQ to XML
xTile...<text>.FirstOrDefault(Function(node) node.@id = "1").SetValue("Text Line 1")

' Set XmlDocument
tileXml.LoadXml(xTile.ToString())
Dim notification = New TileNotification(tileXml)
TileUpdateManager.CreateTileUpdaterForApplication().Update(notification)

That’s all it takes. If you don’t like this template, there’s plenty more where this came from. MSDN has a great page showing each of the tile samples along with the template XML you need to use.

Posted on - Comment
Categories: Linq to XML - WinRT - VB Dev Center -
comments powered by Disqus