WPF - DataGridのセルをコードから選択する (CurrentCellの変更)

プログラムから DataGrid の CurrentCell を設定し、セルを選択するには DataGridCellInfo オブジェクトを生成(new)して代入します。

セルを選択した状態

DataGridのセルをコードから選択

DataGridのセルをコードから選択する方法

行インデックス・列インデックスから DataGridCellInfo オブジェクト を生成し、データグリッドの CurrentCell プロパティに代入します。
using System.Windows.Controls;

int rowIndex = 選択したい行番号;     // 0 ~
int columnIndex = 選択したい列番号;  // 0 ~

// データグリッドにフォーカスが必要
dataGrid.Focus();

// DataGridCellInfo を生成
DataGridCellInfo cellInfo = new DataGridCellInfo(dataGrid.Items[rowIndex], dataGrid.Columns[columnIndex]);

// CurrentCell を設定
dataGrid.CurrentCell = cellInfo;

// 選択中の行を設定
dataGrid.SelectedIndex = rowIndex;

サンプルコード

XXXXX.xaml.cs

画面には次のコントロールが配置されています。

using System.Windows.Controls;

/// <summary>
/// 選択ボタンのクリックイベント
/// </summary>
private void Button_Click(object sender, RoutedEventArgs e)
{
    int rowIndex = 0;
    int columnIndex = 0;

    if (!int.TryParse(this.txtRowNo.Text, out rowIndex))
    {
        MessageBox.Show("行番号を数値に変換できません。");
        return;
    }

    if (!int.TryParse(this.txtColumnNo.Text, out columnIndex))
    {
        MessageBox.Show("列番号を数値に変換できません。");
        return;
    }


    if (rowIndex < 0 || rowIndex >= dataGrid.Items.Count)
    {
        MessageBox.Show("行番号が範囲外です。");
        return;
    }

    if (columnIndex < 0 || columnIndex >= dataGrid.Columns.Count)
    {
        MessageBox.Show("列番号が範囲外です。");
        return;
    }

    // データグリッドにフォーカスが必要
    this.dataGrid.Focus();

    // DataGridCellInfo を生成
    DataGridCellInfo cellInfo = new DataGridCellInfo(this.dataGrid.Items[rowIndex], this.dataGrid.Columns[columnIndex]);

    // CurrentCell を設定
    this.dataGrid.CurrentCell = cellInfo;

    // 選択中の行を設定
    this.dataGrid.SelectedIndex = rowIndex;
}

検証環境

関連ページ