【问题标题】:Delete selected cells content in WPF DataGrid删除 WPF DataGrid 中选定的单元格内容
【发布时间】:2012-11-16 17:59:54
【问题描述】:

我有一个DataGrid 绑定到一个矩阵。 该应用程序的主要逻辑是任何值为 0 的单元格将不显示任何内容(0 = 在我的引用中没有值)。

现在我想要的是,当用户按下删除按钮时,所有选定的单元格都将设置为 0。 我可以用一个单元格轻松做到这一点(因为我会跟踪当前选择的行/列),但我无法正确地得到一个 2x2 的正方形。

我想出的最好方法是使用Binding 魔法,将每个选定单元格的行/列索引设置为0,然后将Binding 的源设置为0。但是,我仍然不能拥有所有的行号(基本上是因为grid.SelectedCellsIEnumerable<DataGridCellInfo>,而我只能得到这个对象的列,我没有办法得到当前行。)

当我只选择一个单元格(或一行)时,它可以使用以下内容:

DataGridRow dataGridRow = (DataGridRow)this.ItemContainerGenerator.ContainerFromItem(grid.CurrentItem);

多选呢?

这里有什么想法吗?谢谢!

【问题讨论】:

    标签: wpf datagrid


    【解决方案1】:

    试试这个来获得选定的单元格值:

    DataGridCellInfo cell = dataGrid1.SelectedCells[0];
    ((TextBlock) cell.Column.GetCellContent(cell.Item)).Text = "";
    

    计算单元格是文本块。

    【讨论】:

    • 感谢您的回答!它工作正常。您是否知道如何让它自动触发 OnCellEditEnding 事件?基本上我在 CellEditEnding 上更新我的绑定。我试图用BeginEdit()EndEdit() 包围你的街区,但它似乎没有奏效:/
    • 如果选中的单元格因为滚动而不可见,它就不起作用了。
    【解决方案2】:
    foreach (DataGridCellInfo cellInfo in grid.SelectedCells)
    {
        DataGridColumn column = cellInfo.Column;
        string propertyName = ((Binding)column.ClipboardContentBinding).Path.Path;
    
        PropertyInfo pi = cellInfo.Item.GetType().GetProperty(propertyName);
        if (pi != null)
        {
            pi.SetValue(cellInfo.Item, null, null);
        }    
    }
    
    ICollectionView cv = CollectionViewSource.GetDefaultView(grid.Items);
    cv.Refresh();
    

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      相关资源
      最近更新 更多