WPFのデータグリッドを使っていると任意の位置にあるセルへフォーカスを移動したいことがよくある。備忘録として自作のC#のコードを記載しておく。引数で指定した行番号 row と列番号 col を持つセルへフォーカスを移動する。最後の引数 IsBeginEdit は移動先のセルを編集状態にするかしないかのフラグとする。SelectionUnit は Cell を想定している。
public void MoveCell(DataGrid dataGrid, int row, int col, bool IsBeginEdit = false)
{
if (dataGrid.SelectionUnit == DataGridSelectionUnit.FullRow)
{
return;
}
if (dataGrid.Visibility != Visibility.Visible)
{
return;
}
if (dataGrid.Items.Count <= 0)
{
return;
}
if (row < 0 || row > dataGrid.Items.Count - 1 || col < 0 || col > dataGrid.Columns.Count - 1)
{
return;
}
dataGrid.Focus();
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.Items[row], dataGrid.Columns[col]);
DataGridCellInfo cellInfo;
dataGrid.SelectedCells.Clear();
if (row < 0 || col < 0)
{
cellInfo = new DataGridCellInfo(dataGrid.Items[0], dataGrid.Columns[0]);
}
else
{
cellInfo = new DataGridCellInfo(dataGrid.Items[row], dataGrid.Columns[col]);
}
dataGrid.SelectedCells.Add(cellInfo);
dataGrid.CurrentCell = cellInfo;
FrameworkElement contentElement = cellInfo.Column.GetCellContent(cellInfo.Item);
if (contentElement is null)
{
return;
}
DataGridCell dgCell = contentElement.Parent as DataGridCell;
if (dgCell is null)
{
return;
}
dgCell.Focus();
if (IsBeginEdit)
{
dataGrid.BeginEdit();
}
}
私がよく使用する場面は、例えばデータグリッド上でリターンキーが押された時である。PreviewKeyDownイベントハンドラでデフォルトの動作をキャンセルした後で(KeyEventArgs.Handledプロパティをtrueに設定)、希望する移動先の行番号と列番号を渡して本関数を呼び出す。
※使用の際は自己責任でお願いします。
コメント