Hello @jm6271 ,
Welcome to Microsoft Q&A!
It is recommended to use Data template selection. The following is a simple code example.
MainWindow.xaml
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="ListVIewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ListVIewTest"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="ListVIewTest">
<Page x:Name="MainPage">
<Page.Resources>
<DataTemplate x:Key="ColorItemTemplate1">
<Border Background="Purple">
<TextBlock Text="{Binding}" Padding="10"/>
</Border>
</DataTemplate>
<DataTemplate x:Key="ColorItemTemplate2">
<Border Background="HotPink">
<TextBlock Text="{Binding}" Padding="10"/>
</Border>
</DataTemplate>
<local:RowColorItemTemplateSelector x:Key="RowColorItemTemplateSelector"
ColorItemTemplate1="{StaticResource ColorItemTemplate1}"
ColorItemTemplate2="{StaticResource ColorItemTemplate2}" />
</Page.Resources>
<Grid>
<ListView ItemsSource="{x:Bind Items}" ItemTemplateSelector="{StaticResource RowColorItemTemplateSelector}"></ListView>
</Grid>
</Page>
</Window>
MainWindow.xaml.cs
public sealed partial class MainWindow : Window
{
public ObservableCollection<string> Items { get; set; }
public MainWindow()
{
this.InitializeComponent();
//MainPage.DataContext = new MainWindowViewModel();
Items = new ObservableCollection<string>
{
"1",
"2",
"3",
"4",
"5",
};
}
}
public class RowColorItemTemplateSelector : DataTemplateSelector
{
public DataTemplate ColorItemTemplate1 { get; set; }
public DataTemplate ColorItemTemplate2 { get; set; }
protected override DataTemplate SelectTemplateCore(object item)
{
int index = Convert.ToInt32(item.ToString());
return index % 2 == 0 ? ColorItemTemplate1 : ColorItemTemplate2;
}
}
Thank you.
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.