SuperJMN
SuperJMN

Reputation: 14002

Creating a DataTemplate in UWP from code

I'm creating a XAML parser and in order to interact with the UWP classes I need to generate a DataTemplate from code.

I have seen that the DataTemplate class has a LoadContent() method, but how can I use it? Is there a method to specify which content has to be loaded?

By the way, I have try to implement the IDataTemplate interface, but since it's internal, I had to derive from DataTemplate.

Upvotes: 0

Views: 1362

Answers (1)

Grace Feng
Grace Feng

Reputation: 16652

I have seen that the DataTemplate class has a LoadContent() method, but how can I use it? Is there a method to specify which content has to be loaded?

You can refer to DataTemplate.LoadContent method, there is sample code in this document showing how to use the LoadContent method to change the appearance of a Border at run time. This is the method to specify which content has to be loaded.

I understand that you may want to create the whole DataTemplate in the code behind using XAML Parser, but not load one which exist in the Resources, then you can code for example like this:

StringReader reader = new StringReader(
   @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">
   <Ellipse Width=""300.5"" Height=""200"" Fill=""Red""/>
   </DataTemplate>");
var template = XamlReader.Load(await reader.ReadToEndAsync());
ListView lv = new ListView();
lv.ItemTemplate = template as DataTemplate;
ObservableCollection<int> coll = new ObservableCollection<int>();
for (int i = 0; i < 20; i++)
{
    coll.Add(i);
}
lv.ItemsSource = coll;
rootGrid.Children.Add(lv);

Here I parsed a DataTemplate from string using XamlReader and applied this DataTemplate as the ItemTemplate of a ListView.

Upvotes: 2

Related Questions