How do I create DataTemplate in win8 (WinRT) App using code behind file i.e. using C# instead of xaml.
Asked
Active
Viewed 2,479 times
3
-
Why you want to do this in codebehind? – Skiba Aug 23 '12 at 10:58
-
@Skiba its a requirement so can you help – CognitiveDesire Aug 23 '12 at 11:07
-
I'm affraid i have no idea how to create dataTemplate in codebehind. However if u need because u need some feature from template I might be able to help with "xamling" it – Skiba Aug 23 '12 at 11:15
-
In all my time with XAML I never had a need to create data template in code. So I'd recommend to make sure you understand your requirements correctly. – Denis Aug 24 '12 at 18:27
-
1Skiba and Denis, you are not only wasting the OP's time, you are wasting the time of all the other people that come looking for a similar solution. If you have nothing to add to the conversation than a declaration of your ignorance, please refrain from cluttering up the board. – Quark Soup Jan 18 '15 at 16:14
1 Answers
4
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; }
}

N G
- 56
- 2