Jan Chalupa
Jan Chalupa

Reputation: 897

Dynamically created list item's template

How can I set template to dynamically created list items?

Something like this:

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

In XAML I have this:

<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>

Upvotes: 0

Views: 788

Answers (2)

Andrii Krupka
Andrii Krupka

Reputation: 4306

If you want create your DataTemplate if code-behind, you can use this mechanism:

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

Upvotes: 1

Tam&#225;s Deme
Tam&#225;s Deme

Reputation: 2228

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

Where this is the page.

EDIT:

Although I don't know if it'll work with x:bind...

Upvotes: 1

Related Questions