【发布时间】:2026-01-30 23:25:01
【问题描述】:
我通过 LoadingRow 事件以编程方式交替行颜色。 这样做的原因是因为我需要在某些行上指定特定的颜色,即标记为删除的行和带有修改数据的行。
这很好用,直到我在 DataGrid 中向上滚动并得到这个非常奇怪的交互,它使行颜色加倍或加倍。
向下滚动时正确显示。
我尝试使用 AlternationIndex 并将 AlternationCount 设置为 2,并使用布尔值在两者之间切换,两者都会导致完全相同的问题。
如果我没有在 LoadingRow 事件中设置它并使用 DataGrid AlternatingRowBackground,当我滚动表格时,行颜色会渗入其他行。
private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
// Get the DataRow corresponding to the DataGridRow that is loading.
var item = e.Row.Item as ExpandoObject;
if (loadedTable.ToDelete.Contains(item))
{
e.Row.Background = new SolidColorBrush(Colors.OrangeRed);
return;
}
else if (loadedTable.Modified.Contains(loadedTable.Rows.IndexOf(item)))
{
e.Row.Background = new SolidColorBrush(Colors.LightYellow);
return;
}
else if (e.Row.AlternationIndex == 0)
{
e.Row.Background = new SolidColorBrush(Colors.WhiteSmoke);
}
else if (e.Row.AlternationIndex == 1)
{
e.Row.Background = new SolidColorBrush(Colors.LightGray);
}
}
<DataGrid CanUserAddRows="False" GridLinesVisibility="All" VerticalGridLinesBrush="Gray" HorizontalGridLinesBrush="Gray"
FontSize="15" FrozenColumnCount ="1" x:Name="xmlData" EnableRowVirtualization="True" AlternationCount="1"
AlternatingRowBackground="LightGray" Background="WhiteSmoke"
Grid.Column="1" Margin="0,-31,5,10" AutoGenerateColumns="False" Grid.Row="2" SelectionUnit="Cell"
PreviewKeyDown="DataGridKeyDown_Event" IsReadOnly="True" CanUserDeleteRows="True"
LoadingRow="dataGrid_LoadingRow"/>
【问题讨论】:
-
可以为您的数据网格添加 xaml 吗?你在做任何虚拟化吗?除了在后面做代码之外,您是否考虑过使用数据网格行样式?我通常使用它,然后在其中使用数据触发器来更改背景颜色。它将遵循您原来的交替或默认背景颜色,并且仅在触发数据触发器时更改。在datatrigger的Binding中可以使用converter来做复杂的逻辑。
-
@JMIII 现在添加了 XML。我认为你和 J.H.建议走的路线,谢谢。