Matt
Matt

Reputation: 22123

In WPF, how can I allow only a single cell to be selected in a DataGrid?

I want it to only be possible to select one cell in a DataGrid. With multi select disabled, you can still select a range of cells, but I want it to only allow a single-cell selection. Is there any way to do this through the properties? Or will I have to intercept the selection and filter out everything but one cell?

Upvotes: 3

Views: 4749

Answers (2)

Adam Houldsworth
Adam Houldsworth

Reputation: 64487

The DataGrid has a SelectionUnit property of type DataGridSelectionUnit, in conjunction with SelectionMode:

The SelectionMode and SelectionUnit properties together define the selection behavior for the DataGrid.

Try setting SelectionUnit to Cell. This will work with both SelectionMode values:

If the selection mode is Extended, the user can select multiple items where the item type is defined by the SelectionUnit property. If the selection mode is Single, the user can only select single items.

To select a single cell, use SelectionMode of Single and SelectionUnit of Cell:

The SelectionMode and SelectionUnit properties together determine how users can select items in a DataGrid. For example, if the SelectionMode is Single and the SelectionUnit is Cell, the user can select only one cell at a time in the DataGrid.

Upvotes: 10

Storm
Storm

Reputation: 682

You need to set the SelectionUnit of the DataGrid. It defines the scope of one selection unit. It can be set to Cell, CellAndRowHeader and FullRow.

Example:

<DataGrid ItemsSource="{Binding Customers}" SelectionMode="Single" SelectionUnit="Cell" />

Upvotes: 3

Related Questions