C# wpf - This code changes the entire ListView background:
public void FillListView(ListView LVw, List liststX)
{
LVw.Items.Clear();
if (liststX.Count > 0) {
for (int iii = 0; iii < liststX.Count; iii++) {
string stName = liststX[iii];
LVw.Items.Add(stName);
if (stName.Contains("blue"))
LVw.Background = Brushes.Blue;
else if (stName.Contains("yellow"))
LVw.Background = Brushes.Yellow;
else if (stName.Contains("black"))
LVw.Background = Brushes.Black;
else if (stName.Contains("red"))
LVw.Background = Brushes.Red;
}
}
}
How do I change the background color for every line in a ListView? Every ListView line background could be different ... one ListView line background could red, the next ListView line background could be blue.
Mithilesh TataPosted Mar 23, 2024, 6:16 AM
To achieve different background colors for each line in a ListView, you should define a DataTemplate for the ListView items and bind the background color property to a property in your data source. Here's how you can modify your code to achieve this:
XAML:
C#
In this code:
ListItemclass is created to hold the name and background color for each item.Backgroundproperty of eachListItem.FillListViewmethod, instead of adding strings directly to the ListView items, you createListItemobjects, set their properties accordingly, and add them to the ListView. This ensures that each item has its own background color.stName, you assign different background colors to eachListItem.