12

私はDataGridWPF コントロールを持っていて、特定のDataGridCell. 行と列のインデックスを知っています。これどうやってするの?

DataGridCellそのコンテンツにアクセスする必要があるため、が必要です。したがって、(たとえば) の列があるDataGridTextColum場合、コンテンツはTextBlockオブジェクトになります。

4

3 に答える 3

4

次のようなコードを使用して、セルを選択できます。

var dataGridCellInfo = new DataGridCellInfo(
    dataGrid.Items[rowNo], dataGrid.Columns[colNo]);

dataGrid.SelectedCells.Clear();
dataGrid.SelectedCells.Add(dataGridCellInfo);
dataGrid.CurrentCell = dataGridCellInfo;

特定のセルの内容を直接更新する方法が見当たらないので、特定のセルの内容を更新するには、次のようにします。

// gets the data item bound to the row that contains the current cell
// and casts to your data type.
var item = dataGrid.CurrentItem as MyDataItem;

if(item != null){
    // update the property on your item associated with column 'n'
    item.MyProperty = "new value";
}
// assuming your data item implements INotifyPropertyChanged the cell will be updated.
于 2012-04-02T14:22:09.457 に答える
2

この拡張メソッドを簡単に使用できます-

public static DataGridRow GetSelectedRow(this DataGrid grid)
{
    return (DataGridRow)grid.ItemContainerGenerator.ContainerFromItem(grid.SelectedItem);
}

既存の行と列の ID で DataGrid のセルを取得できます。

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

grid.ScrollIntoViewDataGrid が仮想化され、必要なセルが現在表示されていない場合に、これを機能させるための鍵です。

詳細については、このリンクを確認してください - Get WPF DataGrid の行とセル

于 2012-06-26T10:35:01.727 に答える