簡體   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