[WPF]DataGridのセル移動をEntarで横に移動させる
こんにちは。
ソリューションSecのHです。
明日はクリスマスですね!🎄
イルミネーションとか見に行きたいですね!
今年からは23日も平日になってしまったのであまりお出かけされる方も多くはないのかな~~と思いますが、
やっぱりクリスマスなのでチキン🍗でも食べて気分を味わいたいですね!!!
さて、今回もWPFの小ネタを少しご紹介します!
普通DataGridでEnterを押すと下にフォーカスが移ってしまうのですが、
それを何とか横に移動させたい!!
ということで、Enterを押してTabを押したときのように横に移動させたいと思います。
今回は動作になるので画像で説明っていうのが難しいのですが
下記画像の赤矢印の方向に動かしたいなと思います。

以下のコードをDataGridのKeyDownイベントに記載します!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
// Enterでフォーカス移動 if(e.Key== Key.Enter) { DataGridColumn currentCol = this.CurrentColumn; bool isLastCol = (currentCol.DisplayIndex == this.Columns.Count - 1); bool isFirstCol = currentCol.DisplayIndex <= 0; int currentRow = this.Items.IndexOf(this.SelectedItem); int rowMax = this.Items.Count; this.CommitEdit(); if (!isLastCol && !isFirstCol) { //行の1つ目の項目と最後の項目以外 //長いので改行 this.CurrentColumn = Keyboard.Modifiers == ModifierKeys.Shift ? this.Columns[currentCol.DisplayIndex - 1] : this.Columns[currentCol.DisplayIndex + 1]; } else if (isLastCol) { //行の最後の項目は次の行の最初に移動または前の項目へ移動 if (Keyboard.Modifiers == ModifierKeys.Shift) { this.CurrentColumn = this.Columns[currentCol.DisplayIndex - 1]; } else { if ((currentRow + 1) != rowMax) { this.SelectedIndex = currentRow + 1; //Thread.Sleep(5000); this.CurrentCell = new DataGridCellInfo(this.Items[currentRow + 1], this.Columns[this.NextReturn]); //先頭列を表示 this.ScrollIntoView(this.Items[currentRow + 1], this.Columns[0]); //次の行に行ったときだけbeginEditして続けて入力できるようにしてもいいかもしれません //this.BeginEdit(); } } } else if(isFirstCol) { //行の最初の項目は次の項目へ移動または次の行の最後に移動 if(Keyboard.Modifiers == ModifierKeys.Shift) { if ((currentRow - 1) >= 0) { this.SelectedIndex = currentRow - 1; this.CurrentCell = new DataGridCellInfo(this.Items[currentRow - 1], this.Columns[this.Columns.Count - 1]); } } else { this.CurrentColumn = this.Columns[currentCol.DisplayIndex + 1]; } } e.Handled = true; } |
これでEnterを押した際にフォーカスが横に動くようになりました!
最後のカラムまで行くと下の行の1番最初に戻ります
Shiftを押しながらEnterを押すと前に戻ります。
WPFが多いですが今後はWEB系の技術なんかもご紹介できればと思います♪
それでは!