WPF DataGrid中的单元格高亮显示 [英] Cell Highlighing in WPF DataGrid
本文介绍了WPF DataGrid中的单元格高亮显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下方法突出显示我的数据网格代码隐藏中的单元格。但问题是,当我滚出视图时,突出显示的细胞会丢失并跳跃。我已将行和列虚拟化都设置为false。请帮忙。
I am using the below method to highlight cells from my code-behind for my data grid. But the problem is that when I scroll out of view, the highlighted cells are getting lost and are jumping around. I have set both row and column virtualization to false. please help.
public void ColourCell(int row, int column, Color color, bool HighlightFlag = true)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized but enable virtualizion is off
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
// now try to bring into view and retreive the cell
if (cell != null)
{
if (HighlightFlag == false)
cell.Background = new SolidColorBrush(Colors.MediumPurple);
else
{
cell.Background = new SolidColorBrush(color);
}
}
}
}
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)DataGridControl.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
row = (DataGridRow)DataGridControl.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
推荐答案
XAML版本要好得多:
http://social.msdn.microsoft.com/Forums/en-US / wpf / thread / a5fd5413-f055-4b56-83af-6d6bdb1d6fe9 / [ ^ ]
The XAML version is much better:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a5fd5413-f055-4b56-83af-6d6bdb1d6fe9/[^]
此代码可以帮助您。
This code will help you.
private void GetCell(DataGridRow row, DataGridColumn column)
{
DependencyObject parent = row;
Lable1:
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var item = VisualTreeHelper.GetChild(parent, i);
if (item is DataGridCellsPresenter)
{
DataGridCellsPresenter presenter = item as DataGridCellsPresenter;
DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(1) as DataGridCell;
cell.Background = Brushes.Red;
break;
}
else
{
parent = item;
goto Lable1;
}
}
}
这篇关于WPF DataGrid中的单元格高亮显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文