繁体   English   中英

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

[英]how to programatically disable a particular cell in WPF DataGrid

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

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

您无法直接在 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;

请注意在某些情况下,需要先加载表单才能进行任何操作。

希望有一天这对某人有所帮助;-)

使用样式,如下所示:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM