私は DataGrid
WPFコントロールと私は特定の DataGridCell
。私は行と列のインデックスを知っています。これどうやってするの?
私は DataGridCell
私はそのコンテンツにアクセスする必要があるからです。だから私が(例えば)列を持っていれば DataGridTextColum
、私のコンテンツは TextBlock
オブジェクト。
回答:
回答№1は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.
回答№2については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.ScrollIntoView
DataGridが仮想化され、必要なセルが現在表示されていない場合にこの作業を行うための鍵です。
詳細については、このリンクをチェックしてください - WPF DataGridの行とセルを取得する
回答№3の場合は1
私が使用したコードは次のとおりです。
/// <summary>
/// Get the cell of the datagrid.
/// </summary>
/// <param name="dataGrid">The data grid in question</param>
/// <param name="cellInfo">The cell information for a row of that datagrid</param>
/// <param name="cellIndex">The row index of the cell to find. </param>
/// <returns>The cell or null</returns>
private DataGridCell TryToFindGridCell(DataGrid dataGrid, DataGridCellInfo cellInfo, int cellIndex = -1)
{
DataGridRow row;
DataGridCell result = null;
if (dataGrid != null && cellInfo != null)
{
if (cellIndex < 0)
{
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromItem(cellInfo.Item);
}
else
{
row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(cellIndex);
}
if (row != null)
{
int columnIndex = dataGrid.Columns.IndexOf(cellInfo.Column);
if (columnIndex > -1)
{
DataGridCellsPresenter presenter = this.FindVisualChild<DataGridCellsPresenter>(row);
if (presenter != null)
{
result = presenter.ItemContainerGenerator.ContainerFromIndex(columnIndex) as DataGridCell;
}
else
{
result = null;
}
}
}
}
return result;
}`
これは、DataGridが既にロードされていることを前提としています(独自のLoadedハンドラを実行しています)。