基于前一行设置DataGrid背景颜色
本文关键字:背景 颜色 DataGrid 设置 于前一 | 更新日期: 2023-09-27 18:29:42
我试图设置一个网格来进行列排序,但我想进行斑马线,只是我希望它基于前一行的值,而不是每隔一行或每x行。即,所有包含0的行都有蓝色背景,下一个值将有白色背景,下个值将是蓝色,等等…
我遇到的问题是,我似乎找不到真正在哪里设置背景色。我使用的是自定义排序器,在重新排序列表并设置数据源后,我尝试在其中设置它,但当设置数据源时,行似乎还不存在。我尝试使用DataContextChanged,但该事件似乎没有启动。
这是我现在拥有的。
namespace Foo.Bar
{
public partial class FooBar
{
List<Bla> ResultList { get; set; }
SolidColorBrush stripeOneColor = new SolidColorBrush(Colors.Gold);
SolidColorBrush stripeTwoColor = new SolidColorBrush(Colors.White);
//*********************************************************************************************
public Consistency()
{
InitializeComponent();
}
//*********************************************************************************************
override protected void PopulateTabWithData()
{
ResultList = GetBlas();
SortAndGroup("Source");
}
//*********************************************************************************************
private void SortAndGroup(string colName)
{
IOrderedEnumerable <Bla> ordered = null;
switch (colName)
{
case "Source":
case "ID":
ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.ID);
break;
case "Name":
ordered = ResultList.OrderBy(r => r.Source).ThenBy(r => r.Name);
break;
case "Message":
ordered = ResultList.OrderBy(r => r.Message);
break;
default:
throw new Exception(colName);
}
ResultList = ordered.ThenBy(r => r.Source).ThenBy(r => r.ID).ToList(); // tie-breakers
consistencyDataGrid.ItemsSource = null;
consistencyDataGrid.ItemsSource = ResultList;
ColorRows();
}
//*********************************************************************************************
private void consistencyDataGrid_Sorting(object sender, System.Windows.Controls.DataGridSortingEventArgs e)
{
SortAndGroup(e.Column.Header.ToString());
e.Handled = true;
}
private void ColorRows()
{
for (var i = 0; i < ResultList.Count; i++)
{
var currentItem = ResultList[i];
var row = myDataGrid.ItemContainerGenerator.ContainerFromItem(currentItem) as DataGridRow;
if (row == null)
{
continue;
}
if (i > 0)
{
var previousItem = ResultList[i - 1];
var previousRow = myDataGrid.ItemContainerGenerator.ContainerFromItem(previousItem) as DataGridRow;
if (currentItem.Source == previousItem.Source)
{
row.Background = previousRow.Background;
}
else
{
if (previousRow.Background == stripeOneColor)
{
row.Background = stripeTwoColor;
}
else
{
row.Background = stripeOneColor;
}
}
}
else
{
row.Background = stripeOneColor;
}
}
}
}
}
}
为LoadingRow添加一个处理程序,并将您的颜色逻辑放在那里:
bool isColorOne = false;
var previousValue = null;
private consistencyDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
// Check current value against previous value
if (previousValue == e...)
{
previousValue = e...;
isColorOne = !isColorOne;
}
if (isColorOne)
{
row.Background = stripeOneColor;
}
else
{
row.Background = stripeTwoColor;
}
}
然后,您可以在排序时根据需要重置isColorOne
和previousValue
的值。