c# - win8中创建DataTemplate

标签 c# windows-8 .net-4.5

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

最佳答案

如果您想根据要显示的内容创建模板,我明白为什么这会很有用。 完成这项工作的关键是 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; }
}

关于c# - win8中创建DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12089943/

相关文章:

c# - 替换所有程序的 Windows 快捷方式

c# - 如何检查 View 状态存在于 asp.net 4.0

javascript - Famo.us 最大接触点(Windows 8 + Chrome)

ASP.NET 模型绑定(bind)、ListView 和 CheckBox.Checked

c# - MachineKey.Protect/Unprotect 的非 ASP.Net 等效项

c# - 为什么我必须使用等待异步运行的方法。如果我不想在继续之前等待方法完成怎么办?

c# - 让 NLog 发送带有正确 header 的 JSON?

c#如何改变托盘图标

windows-8 - 如何使用 gitbash 代替 windows cmd.exe 与meteor Release 0.7.0.1-win2

javascript - Windows 应用商店应用程序 - 从辅助磁贴启动时执行单个任务