2011-10-26 68 views
0

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

现在我想要的是,当用户按下删除按钮,所有选中的单元格将被设置为0. 我可以很容易地做到这一点与一个单元格(因为我跟踪选定的当前行/列),但我无法得到,比方说,一个2×2的正方形。

我想通过使用Binding魔法的最佳方法是获得每个单元格的行/列索引,然后将Binding的源设置为0.但仍然不能全部行号(主要是因为grid.SelectedCellsIEnumerable<DataGridCellInfo>,我只能得到这个对象的列,我没办法得到当前行)。

它工作时我只选择一个单元格(或一行) ,通过使用以下内容:

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

如何多选?

这里的任何想法?谢谢!

回答

2

试试这个让选定的单元格的值:

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

计数的细胞的TextBlocks。

+0

感谢您的回答!它工作正常。你会知道如何使它自动触发OnCellEditEnding事件吗?基本上我更新我的绑定到CellEditEnding。我试着用'BeginEdit()'和'EndEdit()'来包围你的块,但它似乎没有办法:/ – Damascus

+0

不,我不知道。抱歉。 – gcores

+0

如果所选单元格由于滚动而不可见,则不起作用。 – Rover

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(); 
相关问题