Applying DataTemplate programmatically in Windows 8 Store App

Sometime you want to apply dynamic layout and content for Windows Store app. For example, when user click on button or changing the windows orientation. In that case, you could use animation and StoryBoard. But sometime you could not and need to implement by code. In this article I will present to you how to apply DataTemplate for a FlipView control programmatically. You can write down the DataTemplate directly in code or loading from XML file.

To Apply DataTemplate directly from code

You similar following code to apply DataTemplate from code.

StringBuilder templateXml = new StringBuilder();
builder.Append("<DataTemplate xmlns=\"\">");
builder.Append("<!—your layout and content control defines here-->");
DataTemplate template = (DataTemplate)XamlReader.Load(templateXml.ToString());
flipView.ItemTemplate = template;

To Apply DataTemplate from XML file

First of all, your XML template file must be added to your project with Build Action as Content. And the format of the XML template file similar to:

<?xml version="1.0" encoding="utf-8"  ?>
<DataTemplate xmlns="">
<!—Your layout and content control defines here-->

Now in code you will read the xml file similar like this

string xmlTemplatePath = Path.Combine(Package.Current.InstalledLocation.Path, "Templates/DayDetailDataTemplate.xml");
XDocument templateXml = XDocument.Load(xmlTemplatePath);
DataTemplate template = (DataTemplate)XamlReader.Load(templateXml.ToString());
flipView.ItemTemplate = template;


I think this technical is not only used in Windows Store app, but it also can be used in Windows Phone app! Do you think so?

This Post Has 0 Comments

  1. I have fun with, result in I found exactly what I was taking a
    look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye

Leave a Reply