Home
Manage Your Code
Snippet: ListView with alternating background colors and dep. props. used to set the colors (C#)
Title: ListView with alternating background colors and dep. props. used to set the colors Language: C#
Description: This is a child of the ListView class that has alternating background colors Dependency Properties are used to set the colors of the alternating background All instantiated classes are explicitly declared in their specific namespaces. Views: 94
Author: Phil Vollhardt Date Added: 7/16/2008
Copy Code  
1/// <summary>
2/// Alternates the BG Color of each item in the listview
3/// </summary>
4public class AltBGRowsListView : System.Windows.Controls.ListView {
5	protected override void PrepareContainerForItemOverride(System.Windows.DependencyObject element, object item) {
6		base.PrepareContainerForItemOverride(element, item);
7		if (View is System.Windows.Controls.GridView) {
8			int index = ItemContainerGenerator.IndexFromContainer(element);
9			System.Windows.Controls.ListViewItem lvi = element as System.Windows.Controls.ListViewItem;
10			if (0 == index % 2)
11				lvi.Background = this.GetValue(AltBGRowsListView.FirstRowProperty) as System.Windows.Media.SolidColorBrush;
12			else
13				lvi.Background = this.GetValue(AltBGRowsListView.SecondRowProperty) as System.Windows.Media.SolidColorBrush;
14		}
15
16	}
17
18	public static readonly System.Windows.DependencyProperty FirstRowProperty = System.Windows.DependencyProperty.Register("FirstRow", typeof(System.Windows.Media.SolidColorBrush), typeof(AltBGRowsListView), new System.Windows.UIPropertyMetadata(null));
19
20	/// <summary>
21	/// Sets the color of the 1st of the alternating rows
22	/// </summary>
23	public System.Windows.Media.SolidColorBrush FirstRow {
24		get {
25			return (System.Windows.Media.SolidColorBrush)GetValue(FirstRowProperty);
26		}
27		set {
28			SetValue(FirstRowProperty, value);
29		}
30	}
31
32	public static readonly System.Windows.DependencyProperty SecondRowProperty = System.Windows.DependencyProperty.Register("SecondRow", typeof(System.Windows.Media.SolidColorBrush), typeof(AltBGRowsListView), new System.Windows.UIPropertyMetadata(null));
33
34	/// <summary>
35	/// Sets the 2nd color of the alternating rows
36	/// </summary>
37	public System.Windows.Media.SolidColorBrush SecondRow {
38		get {
39			return (System.Windows.Media.SolidColorBrush)GetValue(SecondRowProperty);
40		}
41		set {
42			SetValue(SecondRowProperty, value);
43		}
44	}
45}
Usage
Use like you would use ListView.