【问题标题】:Dynamically created list item's template动态创建的列表项的模板
【发布时间】:2016-02-25 23:54:32
【问题描述】:

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

类似这样的:

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>

【问题讨论】:

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


    【解决方案1】:

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

    this 是页面。

    编辑:

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

    【讨论】:

      【解决方案2】:

      如果你想创建你的DataTemplate if code-behind,你可以使用这个机制:

      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());
      

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-04
        • 2021-10-18
        • 2013-04-08
        相关资源
        最近更新 更多