2016-06-21 23 views
3

DataGridにはDataGridTextColumnsを使用していくつかのデータを表示します。データの一部は変更できます。矢印を使って移動する以外は、すべてうまく動作します。矢印を使ってセルを選択して移動すると、すべて正常に動作しますが、TextBoxCellでも同じことをしたいのです。 私はVisualTreeHelperでビジュアルツリーを通り、次のセルを取得してTextBoxを選択していました。しかし、私はそれぞれのキーを別々に処理しなければならなかったので、非常に長いコードでした。セルが既にこのようにイベントを処理しているとすれば、私はこれを試した:矢印を使用してDataGridのテキストボックスを移動するWPF

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { 
      TextBox tb = sender as TextBox; 
      var temp = VisualTreeHelper.GetParent(tb); 
      var cell = temp as DataGridCell; 
      while (cell == null) { 
       temp = VisualTreeHelper.GetParent(temp); 
       cell = temp as DataGridCell; 
      } 
      if (tb == null) 
       return; 
      cell.RaiseEvent(e); 
} 

私はキーを使うたびに何も起こりません。イベントはちょうどスキップされます。コードはRaiseEventの途中で実行されますが、そのメソッドが呼び出されると何も起こりません。 アイデア ありがとうございます!

答えて

2

他の人がそれに遭遇した場合、問題はイベントでした。 DataGridCellは、KeyDownのみ、PreviewKeyDownを処理しません。解決方法は、イベントを手動で作成してセルに送信することです。あなたが処理されたとしてイベントを置くことができない場合、それが2回発射することを考慮に入れてください。完全なコードは以下のとおりです。

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e) { 
     TextBox tb = sender as TextBox; 
     if (tb != null && isControlKey(e.Key)) { 
      var temp = VisualTreeHelper.GetParent(tb); 
      var cell= temp as DataGridCell; 
      while (cell== null) { 
       temp = VisualTreeHelper.GetParent(temp); 
       cell = temp as DataGridCell; 
      } 

      if (tb == null || cell== null) 
       return; 
      var target = cell; 
      var routedEvent = Keyboard.KeyDownEvent; 

      if (tb.Text.Trim().Length == 0) //Just a check for the value 
       tb.Text = "0"; 

      cell.RaiseEvent(
       new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(cell), 0, e.Key) { 
        RoutedEvent = routedEvent 
       }); 
      e.Handled = true; 
     } 
    } 
関連する問題