We have found three solutions to achieve alternative background scenarios so far. The first one is provided in the previous post. Now we will describe another two.
The second solution:
Derive from ListView, override PrepareContainerForItemOverride method and return the container with the correct background. And in your xaml file, replace ListView with SubListView. When items change, call ListView.Items.Refresh method.
The code is as follows.
public class SubListView : ListView
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
base.PrepareContainerForItemOverride(element, item);
if (View is GridView)
int index = ItemContainerGenerator.IndexFromContainer(element);
ListViewItem lvi = element as ListViewItem;
if (index % 2 == 0)
lvi.Background = Brushes.LightBlue;
}
else
lvi.Background = Brushes.LawnGreen;
The third solution:
Creat a StyleSelector for ListView.ItemContainerStyleSelector property, in which alternate styles. Reset the containerStyleSeletor property when collection changes.
public class ListViewItemStyleSelector : StyleSelector
public override Style SelectStyle(object item, DependencyObject container)
Style st = new Style();
st.TargetType = typeof(ListViewItem);
Setter backGroundSetter = new Setter();
backGroundSetter.Property = ListViewItem.BackgroundProperty;
ListView listView = ItemsControl.ItemsControlFromItemContainer(container) as ListView;
int index = listView.ItemContainerGenerator.IndexFromContainer(container);
backGroundSetter.Value = Brushes.LightBlue;
backGroundSetter.Value = Brushes.LawnGreen;
st.Setters.Add(backGroundSetter);
return st;