Wpf DataGrid - Unable to select cells programmatic

2019-08-14 14:26发布

问题:

I need to select all the cells of a column which header was clicked ,

i took this from the following post :

Selecting all Cells in Column

when a certain column is clicked i wan't to select all it's respected cells.

cs :

    private void OnColumnsClicked(object sender, RoutedEventArgs e)
    {  
        var columnHeader = (DataGridColumnHeader)e.OriginalSource;           
        this.AssociatedObject.SelectedCells.Clear();

        for (int i = 0; i < this.AssociatedObject.Items.Count; i++)
        {
            var cellInfo = new DataGridCellInfo(this.AssociatedObject.Items[i], columnHeader.Column);
            this.AssociatedObject.SelectedCells.Add(cellInfo); // Here is where the Exception is thrown when adding to the SelectedCells collection .
        }                        
    }

the problem is that after adding the second cell to SelectedCells i get the following exception :

 The collection already contains the item.

Important :

When creating cellInfo it has a value for Item and Column properties (See attached image) :

After adding is to SelectedCells , see SelectedCells[0] :

Any ideas why the Cell is being zero'd after adding it to SelectedCells ?

DataGridCellInfo (struct) equality check (from reflector):

internal bool EqualsImpl(DataGridCellInfo cell)
{
     return (((cell._column == this._column) && (cell.Owner == this.Owner)) && (cell._info == this._info));
}