如何使用文件隐藏代码在 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/