简体   繁体   中英

How to create DataTemplate in UWP platform using C# code behind?

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.

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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM