6

WinForms の場合:

var value = DataGridView.Rows[0].Cells[0].Value

WPFで取得する方法はありますか?

4

2 に答える 2

5

Items プロパティを使用して、データ項目に直接アクセスするのが最善の方法だと思います。

var dataItem = dataGrid.Items[0] as ...;

ただし、このクラスを使用してセルを取得し、 GetValue() メソッドで値にアクセスできます(例のようになります)。

ここからのコード: datagrid get cell index

static class DataGridHelper {
    static public DataGridCell GetCell(DataGrid dg, int row, int column) {
        DataGridRow rowContainer = GetRow(dg, row);

        if (rowContainer != null) {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            // try to get the cell but it may possibly be virtualized
            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null) {
                // now try to bring into view and retreive the cell
                dg.ScrollIntoView(rowContainer, dg.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

    static public DataGridRow GetRow(DataGrid dg, int index) {
        DataGridRow row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null) {
            // may be virtualized, bring into view and try again
            dg.ScrollIntoView(dg.Items[index]);
            row = (DataGridRow)dg.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    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;
    }
}
于 2012-11-02T23:45:24.020 に答える
4

通常、これを行う必要はありません。WPF では、datagrid はデータ バインディングで使用することを意図しています。つまり、セルと同じ値を持つ基になるコレクションまたはオブジェクトがあるため、そのコレクション/オブジェクトに直接アクセスする必要があります。セル値にアクセスする必要がある場合は、設計の再検討が必要になる場合があります。

于 2012-11-03T00:46:54.523 に答える