简体   繁体   中英

How to set a Template to a ListViewItem in C#

What steps do I need to follow to create on the XAML a ItemTemplate and set this template to a ListViewItem from the C# code. I know that ListViewItem has the property Template that I can assign one to it, but I did not succeed.

You need to set the ItemTemplate before loading the items in the ListView .

<Page.Resources>
    <DataTemplate x:Name="listViewItemTemplate">
        <TextBlock Text="{Binding}"/>
    </DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListView x:Name="listview"/>
</Grid>

And in the code-behind:

public MainPage()
    {
        this.InitializeComponent();
        listview.ItemTemplate = listViewItemTemplate;
        for (int x = 0; x < 10; x++)
        {
            listview.Items.Add("Item " + x);
        }
    }

I hope this helps.

But in the case of the Template for a single ListViewItem you should be looking for a Style in the generic.xaml file in the SDK folder. It is provided by Microsoft as a default resource file.

You can either copy the default template from the above file or create a new Style property in your page resources and assign this style to your ListViewItem . Have a look here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM