最近遇到個項目,設備上沒有滑鼠,界面為全屏的一個DataGrid,需要實現按小鍵盤的0和1讓DataGrid的當前選中行進行上下滾動 起到重要參考的是: https://blog.csdn.net/sinat_31608641/article/details/105428496 實現後臺滾動到當前選 ...
最近遇到個項目,設備上沒有滑鼠,界面為全屏的一個DataGrid,需要實現按小鍵盤的0和1讓DataGrid的當前選中行進行上下滾動
起到重要參考的是: https://blog.csdn.net/sinat_31608641/article/details/105428496 實現後臺滾動到當前選中項。
現在把主要實現方式做個筆記:
首先,前臺一定要設置VirtualizingStackPanel.IsVirtualizing="False"
接下來,是兩個公共方法:
/// <summary> /// 將SelectedItem滾動為第一行 /// </summary> /// <param name="dataGrid">目標DagaGrid</param> /// <param name="selectedItem">選中項</param> public static void SetSelectedItemFirstRow(object dataGrid, object selectedItem) { //若目標datagrid為空,拋出異常 if (dataGrid == null) { throw new ArgumentNullException("目標無" + dataGrid + "無法轉換為DataGrid"); } //獲取目標DataGrid,為空則拋出異常 System.Windows.Controls.DataGrid dg = dataGrid as System.Windows.Controls.DataGrid; if (dg == null) { throw new ArgumentNullException("目標無" + dataGrid + "無法轉換為DataGrid"); } //數據源為空則返回 if (dg.Items == null || dg.Items.Count < 1) { return; } //獲取焦點,滾動為目標行 dg.Focus(); dg.SelectedItem = selectedItem; dg.CurrentColumn = dg.Columns[0]; dg.ScrollIntoView(dg.SelectedItem, dg.CurrentColumn); } /// <summary> /// 獲取選中的行 /// </summary> /// <param name="datagrid"></param> /// <param name="rowIndex"></param> /// <returns></returns> public static DataGridRow GetDataGridRow(DataGrid datagrid, int rowIndex) { DataGridRow row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); if (row == null) { datagrid.UpdateLayout(); row = (DataGridRow)datagrid.ItemContainerGenerator.ContainerFromIndex(rowIndex); row.IsSelected = true; } return row; }
然後,添加一個窗體的KeyDown事件:
private void UserControl_KeyDown(object sender, KeyEventArgs e) { dgvDeal.Focus(); if (e.Key==Key.NumPad0) { if (dgvDeal.SelectedIndex == dgvDeal.Items.Count-1) { dgvDeal.SelectedIndex = 0; } else { dgvDeal.SelectedIndex = dgvDeal.SelectedIndex + 1; } } else if (e.Key == Key.NumPad1) { if (dgvDeal.SelectedIndex == 0) { dgvDeal.SelectedIndex = dgvDeal.Items.Count-1; } else { dgvDeal.SelectedIndex = dgvDeal.SelectedIndex - 1; } } DataGridRow resRow = GetDataGridRow(dgvDeal, dgvDeal.SelectedIndex); resRow.IsSelected = true; SetSelectedItemFirstRow(dgvDeal, dgvDeal.SelectedItem); }
OK!