WPF Datagrid单元格,cellinfo和selectedcells +自定义选择

我想在WPF数据网格中操作选择,但是我对访问实际单元格并设置焦点并将它们标记为已选中存在问题。

  1. 任何人都可以解释一下:为什么没有一些简单的方法从** DatagridCellInfo **获取** DatagridCell **?
  2. 为什么几乎没有人在使用WPF数据网格? (我没看到很多Q / A投票)
  3. 有没有一种简单的方法如何为WPF数据网格创建自己的选择模式?

我的问题是什么

我想在不按Ctrl的情况下选择更多单元格(逐个)时在WPF Datagrid上进行自定义选择 。 我做得很好但是当我想取消选择一个选定的单元格时,我遇到了问题 – 只需单击它即可。 从列表中删除它不是问题。 问题在于,当它被点击时,它会成为焦点而且是高亮的,所有其他被选中的人都会关闭他们的暮色。 如果我选择另一个未选中的单元格,则所有选定的单元格将再次正确显示。 问题只出在取消选择中。

我的代码:

XAML:

                

我已经在datagrid中填充了我制作的一些随机示例类对象的列表。

C#:

  private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DataGridCell cell = sender as DataGridCell; DataGridCellInfo cellInfo = new DataGridCellInfo(cell); if ((cell.IsSelected)||(selectedList.Contains(cellInfo))||(selectedCellsList.Contains(cell))) { selectedList.Remove(cellInfo); selectedCellsList.Remove(cell); cell.IsSelected = false; mydatagrid.CurrentCell = selectedList[0]; } else { if (selectedList.Count < 7) { selectedList.Add(cellInfo); selectedCellsList.Add(cell); } else { selectedList.RemoveAt(0); selectedList.Add(cellInfo); selectedCellsList.RemoveAt(0); selectedCellsList.Add(cell); } } mydatagrid.SelectedCells.Clear(); mydatagrid.UnselectAll(); foreach (DataGridCell xcell in selectedCellsList) { xcell.IsSelected = true; xcell.Focus(); } } 

如果这段代码对你来说真的很难看,那我很抱歉。 但我还是只是一点点csharpawan。

我在快捷方式中遇到的问题是:单击选定的单元格只会使其高亮显示并聚焦所有其他选定的单元格,这与我希望它完全相反。 (如果我点击其他尚未选中的单元格,它会按照我想要的方式工作。)

回答问题1:从DataGridCellInfo获取DataGridCell的快捷方法:

  public DataGridCell GetDataGridCell(DataGridCellInfo cellInfo) { var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item); if (cellContent != null) return (DataGridCell) cellContent.Parent; return null; }