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

5
我有一个 WPF 数据表格。 请问,如何在程序中禁用 WPF 数据表格中的特定单元格?
2个回答

6

我回答这个问题是因为我遇到了同样的问题,以下是我想出的解决方案。

在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);
    }
}

通过这种方式,我们可以像这样获取第一行第五列的单元格:

dataGrid1.GetCell(0, 4)

现在将列设置为禁用非常容易:

dataGrid1.GetCell(0, 4).IsEnabled = false;

请注意,在某些情况下,必须在表单加载之前才能使所有内容正常工作。
希望这对某个人有帮助。;-)

2

使用样式,就像以下的方式:

<DataGrid.CellStyle>
    <Style TargetType="DataGridCell" >
        <Style.Setters>
            <Setter Property="IsEnabled" Value="False"/>
        </Style.Setters>
    </Style>
</DataGrid.CellStyle>

3
我认为这对他/她没有用,他/她想要以编程的方式禁用它们。 - Lajos Arpad
2
可以使用绑定和值转换器来编程设置IsEnabled。 <Setter Property="IsEnabled" Value="{Binding Index, Converter={StaticResource CellEnabled}}"/> - AndrewBenjamin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接