I m having a WPF DataGrid. Can u please tell , how to programatically disable a particular cell in WPF DataGrid.
Asked
Active
Viewed 7,477 times
2 Answers
6
I'm answering this as I ran into the same issue, this is the solution I came up with.
You can't access cells and rows directly in WPF so we first define some helper extensions.
(Using some of the code from: 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 ;-)

Nebula
- 1,045
- 2
- 11
- 24
2
using styles, as in the following:
<DataGrid.CellStyle>
<Style TargetType="DataGridCell" >
<Style.Setters>
<Setter Property="IsEnabled" Value="False"/>
</Style.Setters>
</Style>
</DataGrid.CellStyle>

MBDevelop
- 103
- 1
- 11
-
3I don't think this will be useful for him/her. He/she wants to programmatically disable them. – Lajos Arpad Oct 20 '11 at 15:24
-
2This can be used to programmatically set IsEnabled by using a Binding and Converter for Value. `
` – AndrewBenjamin Jul 21 '16 at 23:41