【问题标题】:How to create DataTemplate in UWP platform using C# code behind?如何使用 C# 代码在 UWP 平台中创建 DataTemplate?
【发布时间】:2016-12-29 18:21:49
【问题描述】:

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

【问题讨论】:

  • 您很可能问错了问题。您实际需要或想要在代码隐藏中创建 DataTemplate 对象的可能性很低;更有可能的是,您只是不知道如何使用 XAML 完成您想要的。你应该专注于此。如果您坚持在代码隐藏中创建DataTemplate,则需要提供更多细节。包括一个很好的minimal reproducible example,说明您已经尝试过什么,并准确地解释您无法开始工作的具体问题。

标签: c# c#-4.0 uwp


【解决方案1】:

如果您真的想从代码隐藏中创建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());
}

【讨论】:

  • 这在使用任意数据源时如何应用?例如代码不知道字典中的键是什么。链接的解决方案似乎适用于 WPF,而不是 UWP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-25
  • 2020-04-03
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 2022-10-14
相关资源
最近更新 更多