【发布时间】:2018-09-23 01:32:59
【问题描述】:
当用户按下箭头键时,我正在尝试选择 Datagrid 中的第一行,即 Key.Down 事件。
它现在可以工作,但不知何故它会选择第二行,即使我通过索引 [0]...
我创建了 SelectRowByIndex 方法,它应该选择我的 Datagrid 的第一行,它看起来像这样:
private static void SelectRowByIndex(DataGrid dataGrid, int rowIndex)
{
if (!dataGrid.SelectionUnit.Equals(DataGridSelectionUnit.FullRow))
throw new ArgumentException("The SelectionUnit of the DataGrid must be set to FullRow.");
if (rowIndex < 0 || rowIndex > (dataGrid.Items.Count - 1))
throw new ArgumentException(string.Format("{0} is an invalid row index.", rowIndex));
dataGrid.SelectedItems.Clear();
object item = dataGrid.Items[rowIndex];
dataGrid.SelectedItem = item;
DataGridRow row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
if (row == null)
{
//Moram dodati BillItemTemp u slučaju da je virtualized away
dataGrid.ScrollIntoView(item);
row = dataGrid.ItemContainerGenerator.ContainerFromIndex(rowIndex) as DataGridRow;
}
if (row != null)
{
DataGridCell cell = GetCell(dataGrid, row, 0);
if (cell != null)
cell.Focus();
}
}
private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
{
if (rowContainer != null)
{
System.Windows.Controls.Primitives.DataGridCellsPresenter presenter
= FindVisualChild<System.Windows.Controls.Primitives.DataGridCellsPresenter>(rowContainer);
if (presenter == null)
{
rowContainer.ApplyTemplate();
presenter = FindVisualChild<System.Windows.Controls.Primitives.DataGridCellsPresenter>(rowContainer);
}
if (presenter != null)
{
DataGridCell cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
if (cell == null)
{
dataGrid.ScrollIntoView(rowContainer, dataGrid.Columns[column]);
cell = presenter.ItemContainerGenerator.ContainerFromIndex(column) as DataGridCell;
}
return cell;
}
}
return null;
}
之后,我在加载表单时在构造函数中调用了它:
this.PreviewKeyDown += (s, e) =>
{
if (e.Key == Key.Down && dtgProducts.HasItems)
SelectRowByIndex(dtgProducts, 0);
};
但不知何故它选择了第二行?而不是第一个……怎么会?
当我一直按 Key.Down 时,我需要得到保护,不要一直选择同一行..
【问题讨论】: