gpt4 book ai didi

WPF - 如何从 DataGridRow 中获取单元格?

转载 作者:行者123 更新时间:2023-12-04 02:59:58 25 4
gpt4 key购买 nike

我有一个具有交替行背景颜色的数据绑定(bind) DataGrid。我想根据单元格包含的数据对单元格进行不同的着色。我已经尝试过这个线程建议的解决方案

http://wpf.codeplex.com/Thread/View.aspx?ThreadId=51143

但,

DataGridCellsPresenter 演示者 = GetVisualChild(row)

总是返回 null。

我在用

    public 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;
}

但是 DataGridRow 的 VisualTreeHelper.GetChildrenCount() 总是返回 0。我已经验证 DataGridRow 不为空并且已经填充了数据。任何帮助表示赞赏。

谢谢。

最佳答案

如果您知道要访问的单元格的行和索引,那么您可以在代码中执行以下操作:

//here's usage
var cell = myDataGrid.GetCell(row, columnIndex);
if(cell != null)
cell.Background = Brushes.Green;

数据网格扩展:
public static class DataGridExtensions
{
public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int columnIndex = 0)
{
if (row == null) return null;

var presenter = row.FindVisualChild<DataGridCellsPresenter>();
if (presenter == null) return null;

var cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);
if (cell != null) return cell;

// now try to bring into view and retreive the cell
grid.ScrollIntoView(row, grid.Columns[columnIndex]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex);

return cell;
}

关于WPF - 如何从 DataGridRow 中获取单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3671003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com