删除WPF DataGrid中的选定单元格内容

时间:2011-10-26 12:50:37

标签: wpf datagrid

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

现在我想要的是,当用户按下删除按钮时,所有选中的单元格将被设置为0。 我可以轻松地使用一个单元格(因为我跟踪所选的当前行/列),但是我不能正确地得到2x2正方形。

我使用Binding魔法计算出来的最佳方法是选择每个单元格的行/列索引,然后将Binding的源设置为0.但是,我不能拥有所有行号(基本上因为grid.SelectedCellsIEnumerable<DataGridCellInfo>,我只能获得带有此对象的列,我无法获取当前行。)

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

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

多重选择怎么样?

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

2 个答案:

答案 0 :(得分:2)

尝试此操作以获取所选单元格值:

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

计算单元格是文本块。

答案 1 :(得分:1)

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();