WPF 后台实现按数字键滚动DataGrid 当前选中项
最近遇到个项目,设备上没有鼠标,界面为全屏的一个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!
记录和分享用过的技术、基础、方法