如何以编程方式禁用WPF DataGrid中的特定单元格

Abh*_*bhi 4 .net c# wpf gridview

我有一个WPF DataGrid.你可以告诉我,如何以编程方式禁用WPF DataGrid中的特定单元格.

Neb*_*ula 5

当我遇到同样的问题时,我正在回答这个问题,这是我提出的解决方案.

您无法直接在WPF中访问单元格和行,因此我们首先定义一些帮助程序扩展.

(使用以下代码中的一些代码: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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个,我们可以得到第一行,第五列的单元格,如下所示:

dataGrid1.GetCell(0, 4)
Run Code Online (Sandbox Code Playgroud)

因此,将列设置为禁用现在非常简单:

dataGrid1.GetCell(0, 4).IsEnabled = false;
Run Code Online (Sandbox Code Playgroud)

请注意在某些情况下,必须在任何此类工作之前加载表单.

希望有一天能帮到某人;-)


MBD*_*lop 2

使用样式,如下所示:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell" >
        <Style.Setters>
            <Setter Property="IsEnabled" Value="False"/>
        </Style.Setters>
    </Style>
</DataGrid.CellStyle>
Run Code Online (Sandbox Code Playgroud)

  • 我认为这对他/她没有用。他/她想以编程方式禁用它们。 (3认同)
  • 这可用于通过使用 Binding and Converter for Value 以编程方式设置 IsEnabled。`&lt;Setter Property="IsEnabled" Value="{绑定索引,转换器={StaticResource CellEnabled}}"/&gt;` (2认同)