Dante
Dante

Reputation: 3316

Select Multiple Rows or Single Cell only in DataGrid

I am working on a WPF project with DataGrids, I am trying to enable the user to select as many rows as he wants or only a single cell, ie disable to select cells ranges. But I havent been able to do that.

Is this possible?

I have tried the following code:

public MyDataGrid : DataGrid
{
    public ExtendedDataGrid()
    {
        SelectionMode = DataGridSelectionMode.Extended;
        SelectionUnit = DataGridSelectionUnit.CellOrRowHeader;
        this.SelectedCellsChanged += new SelectedCellsChangedEventHandler(MyDataGrid_SelectedCellsChanged);
    }

    void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        if (this.SelectedCells.Count > 1)
        {                
            DataGridCellInfo currentCell = this.CurrentCell;
            this.SelectedCells.Clear();
            this.CurrentCell = currentCell;
        }
    }

But this code does not allow me to select a full row.

So, is there a way to select as many rows as I need but preventing the user from selecting a cell range??

Thanks in advance.

Upvotes: 0

Views: 1271

Answers (1)

Dante
Dante

Reputation: 3316

I think I have solved my problem:

private void MyDataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
    {
        int columnsCount = this.Columns.Count;
        int selectedCells = SelectedCells.Count;
        int selectedItems = SelectedItems.Count;

        if (selectedCells > 1)
        {
            if (selectedItems == 0 || selectedCells % selectedItems != 0)
            {
                DataGridCellInfo cellInfo = SelectedCells[0];
                SelectedCells.Clear();
                SelectedCells.Add(cellInfo);
                CurrentCell = SelectedCells[0];
            }
        }
    }

I know this is not an elegant solution but so far this works as espected, I would appreciate if anyone else has a better solution

Upvotes: 1

Related Questions