如何使用C#代码在UWP平台中创建DataTemplate?

时间:2016-08-23 04:34:17

标签: c# c#-4.0 uwp

我需要在后面使用C#代码在UWP平台中创建DataTemplate。我已经尝试了WPF平台中给出的大部分解决方案,所以请任何人都可以分享你在UWP平台上使用c#作为代码创建dataTemplate的想法。

1 个答案:

答案 0 :(得分:5)

如果您真的想从代码隐藏中创建DataTemplate,请参阅this answer。但除非您有特定的理由这样做,否则在XAML中创建它会更简单,例如在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>

从您的代码隐藏:

public MainPage()
{
    this.InitializeComponent();

    thing.ItemTemplate = (DataTemplate)this.Resources["templateEmployee"];

    thing.Items.Add(new object());
    thing.Items.Add(new object());
}