WPFでフォーカスを移動するには、TABキーまたはマウスクリックが標準。
DataGridも同じ。これが結構面倒。
特に自分のPCにはテンキーが付いているが、TABキーを使うとなると、効果半減。
バタバタ入力するには、ヤッパリ Enterキーでフォーカス移動したい。
同じような考えの人はいるもので、ここにヒントが。ただリンク先の方法そのままでは、フォーカスが右下方向に移動してしまう。(SilverLightとWPFの違いかな?)
自分がやりたいのは、DataGrid全体が入力項目で
- Enterキーで、フォーカスを右へ
- 右端の項目で、Enterキー押下の場合 次行の先頭へ
前述のサイトを参考に、作ったコントロールを下に示す。
using System.Windows.Controls;
using System.Windows.Input;
namespace mbpm
{
public class CustomDataGrid : DataGrid
{
public CustomDataGrid() : base()
{
}
protected override void OnKeyDown(KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.MoveNextCell();
e.Handled = true;
}
else
{
base.OnKeyDown(e);
}
}
private void MoveNextCell()
{
DataGridColumn currentcol = this.CurrentColumn;
// 現在のカラムが最大かどうか
bool isLastCol = (currentcol.DisplayIndex == this.Columns.Count - 1);
if (!isLastCol)
{
// 編集を終了して次のカラムへ
this.CommitEdit();
this.CurrentColumn = this.Columns[currentcol.DisplayIndex + 1];
this.BeginEdit();
}
else
{
// 現在行取得
int currentrow = this.Items.IndexOf(this.SelectedItem);
// 最大行数
int rowMax = this.Items.Count;
if ((currentrow + 1) != rowMax)
{
// 編集を終了して次行の先頭へ
this.CommitEdit();
this.SelectedIndex = currentrow + 1;
this.CurrentCell = new DataGridCellInfo(this.Items[currentrow + 1], this.Columns[0]);
this.BeginEdit();
}
}
}
}
}
参考までに XAMLでの指定は
前略 xmlns:my="clr-namespace:mbpm.classes" 中略 <my:CustomDataGrid ・・・・・> 以下省略
参考URL
https://social.msdn.microsoft.com/Forums/ja-JP/e9909a42-ce31-4b1f-9443-d5fa77c76a77/datagridenter?forum=silvelightdotnetja
http://gacken.com/wp/program/wpf/570/