动态创建列表项的模板

时间:2016-02-25 23:54:33

标签: c# xaml listview windows-10 win-universal-app

如何将模板设置为动态创建的列表项?

这样的事情:

ListView listView = new ListView();
listView.ItemsSource = source.Articles;
listView.Template = ???;
listView.IsItemClickEnabled = true;
listView.ItemClick += OpenArticle_ItemClick;
listView.SelectionMode = ListViewSelectionMode.None;`

在XAML中,我有这个:

<Page.Resources>
    <DataTemplate x:Key="MainItemTemplate" x:DataType="data:Source">
        <Grid IsTapEnabled="False">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
            <StackPanel Grid.Column="1" Orientation="Vertical" Margin="0, 10, 0, 10">
                <TextBlock FontSize="20" Text="{x:Bind Title}" TextWrapping="WrapWholeWords" TextLineBounds="TrimToBaseline" Margin="0, 0, 0, 7" />
                <TextBlock FontSize="12" Text="{x:Bind Date, Converter={StaticResource ConverterDateToHumanReadable}}" Opacity="0.4" />
                <TextBlock FontSize="16" Text="{x:Bind Content }" Opacity="0.8" />
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

2 个答案:

答案 0 :(得分:1)

listView.ItemTemplate = (DataTemplate) this.Resources["MainItemTemplate"];

页面this的位置。

编辑:

虽然我不知道它是否适用于x:bind ...

答案 1 :(得分:1)

如果您想在代码隐藏时创建DataTemplate,可以使用此机制:

StringBuilder sb = new StringBuilder();


sb.Append("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">");
sb.Append("<Grid Width=\"200\" Height=\"100\">");
sb.Append("<StackPanel>");
sb.Append("<StackPanel Orientation=\"Horizontal\" Margin=\"3,3,0,3\"><TextBlock Text=\"Name:\" Style=\"{StaticResource AppBodyTextStyle}\" Margin=\"0,0,5,0\"/><TextBlock Text=\"{Binding Name}\" Style=\"{StaticResource AppBodyTextStyle}\"/></StackPanel>");
sb.Append("<StackPanel Orientation=\"Horizontal\" Margin=\"3,3,0,3\"><TextBlock Text=\"Price:\" Style=\"{StaticResource AppBodyTextStyle}\" Margin=\"0,0,5,0\"/><TextBlock Text=\"{Binding Price}\" Style=\"{StaticResource AppBodyTextStyle}\"/></StackPanel>");
sb.Append("<StackPanel Orientation=\"Horizontal\" Margin=\"3,3,0,3\"><TextBlock Text=\"Author:\" Style=\"{StaticResource AppBodyTextStyle}\" Margin=\"0,0,5,0\"/><TextBlock Text=\"{Binding Author}\" Style=\"{StaticResource AppBodyTextStyle}\"/></StackPanel>");
sb.Append("</StackPanel>");
sb.Append("</Grid>");
sb.Append("</DataTemplate>");


DataTemplate datatemplate = (DataTemplate)XamlReader.Load(sb.ToString());