basquang™ on clouds

April 12, 2013

Applying DataTemplate programmatically in Windows 8 Store App

Filed under: Windows Phone,Windows Store 8 — basquang @ 12:04 PM
Tags:

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=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">");
builder.Append("<!—your layout and content control defines here-->");
builder.Append("</DataTemplate>");
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="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<!—Your layout and content control defines here-->
</DataTemplate>

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;

Conclusion

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?

Advertisements

1 Comment »

  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

    Comment by www.finanz-news.info — May 8, 2013 @ 10:35 PM | Reply


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: