【问题标题】:Selective selecting cells in Datagrid WPFDatagrid WPF中的选择性选择单元格
【发布时间】:2020-06-26 18:07:42
【问题描述】:

我有带有选项的 datagrid wpf:

SelectionUnit="Cell"
SelectionMode="Extended"

Datagrid 有 10 列。我需要的是只选择例如1-4 和 8-10 列 - 当我将鼠标指针拖动到所有数据网格单元格上时,跳过 5-7 列。是否有可能做到这一点?我尝试引发 SelectedCellsChanged 事件并从 DataGrid.SelectedCells 中删除项目,但随后出现异常:

此集合不支持使用特定索引更改值。

更多信息:我有 10 列 x n 行的表格。所有列都带有文本值。行代表员工。列代表天数 - 其中一些是非工作日的周六/周日。单元格值在行和列中可以相同。我希望有可能通过将鼠标指针拖动到数据网格上来选择所有单元格,但跳过选择可能位于列中间的这些星期六/星期日。

【问题讨论】:

  • 你想通过选择性选择单元格来实现什么?

标签: c# wpf datagrid


【解决方案1】:

您可以使用单元格的索引来选择特定列的所有单元格 并使用 System.Collections.Generic.IList 和 System.Collections.Generic.KeyValuePair

更多信息:

You can see here

【讨论】:

    【解决方案2】:

    在 DataGrid XAML 中,为 SelectedCellsChanged 设置事件处理程序:

    SelectedCellsChanged="CustomGrid_SelectedCellsChanged"
    

    现在,在您的代码隐藏中,添加事件处理程序的代码如下:

    private void CustomGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        foreach(DataGridCellInfo cellInfo in minorGrid.SelectedCells)  // For each selected cell
        {
            DataGridCell cell = GetDataGridCell(cellInfo); // get the cell
            string cellText = ((TextBlock)cell.Content).Text; // get the text of the cell
            if (cellText.ToLower().Contains("off"))  // If meets the conditino
                cell.IsSelected = false;  // unselect the cell           
        }
    }
    
    private DataGridCell GetCell(DataGridCellInfo cellInfo)
    {
        var cellContent = cellInfo.Column.GetCellContent(cellInfo.Item);
        if (cellContent != null)
            return (DataGridCell)cellContent.Parent;
    
        return null;
    }
    

    当一个单元格被选中时,我们不会在 SelectedCells 列表中获得 DataGridCell 对象,而是获得 DataGridCellInfo 对象。为了获取 DataGridCell 对象,我提供了一个方法。一旦我们得到单元格对象,我们就可以对单元格执行逻辑。 这将从您的选择中取消选择所有带有“关闭”文本的单元格,这可能是节假日的情况:)。

    同样,如果列标题包含“星期六”或“星期日”,您也可以取消选择整个列,具体取决于您对列的命名方式。只需更改以下几行

    string cellText = ((TextBlock)cell.Content).Text; // get the text of the cell
    if (cellText.ToLower().Contains("off"))  // If meets the conditino
        cell.IsSelected = false;  // unselect the cell 
    

    string headerText = cell.Column.Header.ToString();
    if (headerText.ToLower().Contains("saturday") || headerText.ToLower().Contains("sunday"))  // If meets the conditino
        cell.IsSelected = false;  // unselect the cell  
    

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 2021-03-29
      • 2015-04-12
      • 2016-01-11
      • 2017-07-14
      • 2013-06-08
      • 2016-05-28
      相关资源
      最近更新 更多