私はDataGrid
WPF コントロールを持っていて、特定のDataGridCell
. 行と列のインデックスを知っています。これどうやってするの?
DataGridCell
そのコンテンツにアクセスする必要があるため、が必要です。したがって、(たとえば) の列があるDataGridTextColum
場合、コンテンツはTextBlock
オブジェクトになります。
私はDataGrid
WPF コントロールを持っていて、特定のDataGridCell
. 行と列のインデックスを知っています。これどうやってするの?
DataGridCell
そのコンテンツにアクセスする必要があるため、が必要です。したがって、(たとえば) の列があるDataGridTextColum
場合、コンテンツはTextBlock
オブジェクトになります。
次のようなコードを使用して、セルを選択できます。
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.
この拡張メソッドを簡単に使用できます-
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.ScrollIntoView
DataGrid が仮想化され、必要なセルが現在表示されていない場合に、これを機能させるための鍵です。
詳細については、このリンクを確認してください - Get WPF DataGrid の行とセル