I need to create the DataTemplate in UWP platform using C# code behind. I have tried most of the solution given in the WPF platform so please anyone can share you idea to create dataTemplate in UWP platform using c# as code behind.
Asked
Active
Viewed 3,143 times
1
-
2Most likely you are asking the wrong question. The odds that you actually need or want to create the `DataTemplate` object in code-behind are low; more likely, you just don't know how to accomplish what you want using XAML. You should focus on that. If you insist on creating the `DataTemplate` in code-behind, you need to provide more specifics. Include a good [mcve] that shows what you've tried, and explain _precisely_ what specific issue you are unable to get to work. – Peter Duniho Aug 23 '16 at 04:51
1 Answers
6
If you really want to create a DataTemplate
from code-behind, please see this answer. But unless you have a specific reason to do that, it's much simpler to create it in XAML, for example in your Page.Resources
.
<Page (all the xmlns declarations here) >
<Page.Resources>
<DataTemplate x:Key="templateEmployee">
<StackPanel>
<TextBlock Text="My Name"/>
<TextBlock Text="My Age"/>
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView Name="thing">
...
</ListView>
</Grid>
</Page>
And from your code-behind :
public MainPage()
{
this.InitializeComponent();
thing.ItemTemplate = (DataTemplate)this.Resources["templateEmployee"];
thing.Items.Add(new object());
thing.Items.Add(new object());
}

Community
- 1
- 1

Arctic Vowel
- 1,492
- 1
- 22
- 34
-
1How does this apply when working with an arbitrary data source? e.g. The code doesn't know what the keys are in the dictionary. The linked solution seems to be geared for WPF, not UWP. – CXL Dec 27 '19 at 03:41