Create DataTemplate in win8
.net-4.5, c#, windows-8
Solution
I can see why this might be useful if you want to create the template depending on what kind of thing you're displaying. The key to making this work is Windows.UI.Xaml.Markup.XamlReader.Load(). It takes a string containing your data template and parses it into a DataTemplate object. THen you can assign that object to wherever you want to use it. In the example below, I assign it to the ItemTemplate field of a ListView.
Here is some XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="MyListView"/>
</Grid>
And here is the code-behind that creates the DataTemplate:
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var items = new List<MyItem>
{
new MyItem { Foo = "Hello", Bar = "World" },
new MyItem { Foo = "Just an", Bar = "Example" }
};
MyListView.ItemsSource = items;
var str = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
"<Border Background=\"Blue\" BorderBrush=\"Green\" BorderThickness=\"2\">" +
"<StackPanel Orientation=\"Vertical\">" +
"<TextBlock Text=\"{Binding Foo}\"/>" +
"<TextBlock Text=\"{Binding Bar}\"/>" +
"</StackPanel>" +
"</Border>" +
"</DataTemplate>";
DataTemplate template = (DataTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(str);
MyListView.ItemTemplate = template;
}
}
public class MyItem
{
public string Foo { get; set; }
public string Bar { get; set; }
}
Problem
How do I create DataTemplate in win8 (WinRT) App using code behind file i.e. using C# instead of xaml.