C# 在win8中创建数据模板

C# 在win8中创建数据模板,c#,windows-8,.net-4.5,C#,Windows 8,.net 4.5,如何在win8(WinRT)应用程序中使用代码隐藏文件(即使用C#而不是xaml)创建DataTemplate。如果您想根据显示的内容创建模板,我可以理解为什么这可能很有用。 实现这一点的关键是Windows.UI.Xaml.Markup.XamlReader.Load()。它获取包含数据模板的字符串,并将其解析为DataTemplate对象。然后,您可以将该对象指定到您想要使用它的任何位置。在下面的示例中,我将其分配给ListView的ItemTemplate字段 以下是一些XAML: <

如何在win8(WinRT)应用程序中使用代码隐藏文件(即使用C#而不是xaml)创建DataTemplate。

如果您想根据显示的内容创建模板,我可以理解为什么这可能很有用。 实现这一点的关键是Windows.UI.Xaml.Markup.XamlReader.Load()。它获取包含数据模板的字符串,并将其解析为DataTemplate对象。然后,您可以将该对象指定到您想要使用它的任何位置。在下面的示例中,我将其分配给ListView的ItemTemplate字段

以下是一些XAML:

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <ListView x:Name="MyListView"/>
</Grid>

下面是创建DataTemplate的代码:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        var items = new List<MyItem>
        {
            new MyItem { Foo = "Hello", Bar = "World" },
            new MyItem { Foo = "Just an", Bar = "Example" }
        };
        MyListView.ItemsSource = items;

        var str = "<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +
                "<Border Background=\"Blue\" BorderBrush=\"Green\" BorderThickness=\"2\">" +
                    "<StackPanel Orientation=\"Vertical\">" +
                        "<TextBlock Text=\"{Binding Foo}\"/>" +
                        "<TextBlock Text=\"{Binding Bar}\"/>" +
                    "</StackPanel>" +
                "</Border>" +
            "</DataTemplate>";
        DataTemplate template = (DataTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(str);
        MyListView.ItemTemplate = template;
    }
}

public class MyItem
{
    public string Foo { get; set; }
    public string Bar { get; set; }
}
公共密封部分类主页面:第页
{
公共主页()
{
this.InitializeComponent();
}
受保护的覆盖无效OnNavigatedTo(NavigationEventArgs e)
{
var items=新列表
{
新的MyItem{Foo=“Hello”,Bar=“World”},
新建MyItem{Foo=“Just an”,Bar=“Example”}
};
MyListView.ItemsSource=项目;
var str=“”+
"" +
"" +
"" +
"" +
"" +
"" +
"";
DataTemplate=(DataTemplate)Windows.UI.Xaml.Markup.XamlReader.Load(str);
MyListView.ItemTemplate=模板;
}
}
公共类MyItem
{
公共字符串Foo{get;set;}
公共字符串条{get;set;}
}

为什么要在codebehind中执行此操作?@Skiba这是一项要求,因此您可以帮助我。我很惊讶,我不知道如何在codebehind中创建数据模板。然而,如果您需要,因为您需要模板中的某些功能,我可能能够帮助您实现“xamling”,在使用XAML的所有时间里,我从未需要在代码中创建数据模板。因此,我建议您确保正确理解您的需求。Skiba和Denis,您不仅浪费了OP的时间,也浪费了所有其他寻求类似解决方案的人的时间。如果你在谈话中除了声明你的无知之外没有什么要补充的,请不要把黑板弄得乱七八糟。