更改WPF Datagrid中单个单元格的颜色 [英] Changing color of a single cell in WPF Datagrid

查看:453
本文介绍了更改WPF Datagrid中单个单元格的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF Datagrid,具有可变的列数,并在运行时使用String [] []的二维数组填充。

I have a WPF Datagrid with variable number of columns and populated at runtime with a 2D array of String[][].

String[] data = .....;

datagrid.ItemsSource = data;

我需要根据其值对单元格颜色进行排序。但是这些值由用户在执行期间定义。我发现的有关更改单元格颜色的大多数示例都在XAML上使用了Triggers,并且该值在设计时是已知的。

I need to chance cell colors based on its values. But these values are defined by the user during execution. Most examples I found about changing cell colors use Triggers on the XAML and the value is known in design time.

因此,我正在像这样更改单元格的背景:

So I'm changing the background of the cell like this:

DataGridCell cell = DataGridUtils.GetCell(datagrid, i, j);

cell.Background = new SolidColorBrush(Colors.DarkGreen);

和GetCell函数:

And the GetCell function:

private DataGridCell GetCell(int rowIndex, int colIndex, DataGrid dg)
{
    DataGridRow row = dg.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
    DataGridCellsPresenter p = GetVisualChild<DataGridCellsPresenter>(row);
    DataGridCell cell = p.ItemContainerGenerator.ContainerFromIndex(colIndex) as DataGridCell;

    return cell;
}

乍看起来似乎还可以,我可以看到带有该值为绿色。但是,如果我一直向下滚动数据网格,然后以绿色更改向上返回单元格,则执行另一个随机单元格,而更多的单元格将变为绿色。如果我一直在绿色中上下移动单元格,那么它们会随机变化。

At first glance it seems to be doing ok, I can see the cell with that value in green. But if I scroll the datagrid all the way down and then go back up the cell in green changes do another random cell nad more cells are turning green. If I keep going up and down the cells in green keep changing randomly.

我知道这听起来很奇怪,但是代码中只有一个地方会更改单元格颜色,并且单击按钮即可。我不知道滚动数据网格时怎么可能。

I know this sounds very weird, but there's only one place in code that changes cell colors, and it's in a button click. I don't know how this could be happening when scrolling the datagrid.

我在某处读到ItemContainerGenerator并不是一个很好的解决方案,应该避免。但这是我设法完成这项工作的唯一方法。

I read somewhere that ItemContainerGenerator it's not an elegant solution and should be avoided. But it's the only way I managed to make this work.

是否有更好的方法来更改单元格的背景颜色?我可以在不知道设计时的值的情况下使用触发器执行此操作吗?如果是,怎么办?

Is there better way to change background color of a cell? Can I do this with Triggers without knowing the values at design time? If so, how?

推荐答案

DataGrid 具有 VirtualizationMode 默认为 Recycling ,这意味着它将重复使用生成的 DataCell 提高性能。不必创建 n次的控件。

DataGrid has VirtualizationMode default to Recycling which means it'll reuse the DataCell that it generated to improve performance. It won't have to create n times of controls.

将此控件添加到 DataGrid

VirtualizingStackPanel.VirtualizationMode="Standard"

请注意,这会影响您的表现,WPF会产生 n次的控制权。

Be aware that it'll affect your performance and WPF will create n times of control.

这篇关于更改WPF Datagrid中单个单元格的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆