如何以编程方式禁用 WPF DataGrid 中的特定单元格 [英] how to programatically disable a particular cell in WPF DataGrid
问题描述
我有一个 WPF DataGrid.你能告诉我,如何以编程方式禁用 WPF DataGrid 中的特定单元格.
I m having a WPF DataGrid. Can u please tell , how to programatically disable a particular cell in WPF DataGrid.
推荐答案
我正在回答这个问题,因为我遇到了同样的问题,这是我想出的解决方案.
I'm answering this as I ran into the same issue, this is the solution I came up with.
您无法在 WPF 中直接访问单元格和行,因此我们首先定义一些辅助扩展.
You can't access cells and rows directly in WPF so we first define some helper extensions.
(使用以下代码:http://techiethings.blogspot.com/2010/05/get-wpf-datagrid-row-and-cell.html)
public static class DataGridExtensions
{
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;
}
public static DataGridRow GetRow(this DataGrid grid, int index)
{
DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// May be virtualized, bring into view and try again.
grid.UpdateLayout();
grid.ScrollIntoView(grid.Items[index]);
row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
public static DataGridCell GetCell(this DataGrid grid, DataGridRow row, int column)
{
if (row != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(row);
if (presenter == null)
{
grid.ScrollIntoView(row, grid.Columns[column]);
presenter = GetVisualChild<DataGridCellsPresenter>(row);
}
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
return cell;
}
return null;
}
public static DataGridCell GetCell(this DataGrid grid, int row, int column)
{
DataGridRow gridRow = GetRow(grid, row);
return GetCell(grid, gridRow, column);
}
}
这样我们就可以得到第一行第五列的单元格,如下所示:
With this we can get the cell at the first row, fifth column like this:
dataGrid1.GetCell(0, 4)
所以现在将列设置为禁用非常简单:
So to set the column to disabled is now really easy:
dataGrid1.GetCell(0, 4).IsEnabled = false;
请注意在某些情况下,必须先加载表单,然后才能进行任何操作.
Please note In some cases it is necessary for the form to load before any of this works.
希望有一天这对某人有所帮助;-)
Hope this helps someone someday ;-)
这篇关于如何以编程方式禁用 WPF DataGrid 中的特定单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!