IanR
IanR

Reputation: 4773

Prevent disabled rows in a WPF DataGrid being selected

I have a DataGrid where some rows are disabled based on a property of the items in the grid...

<DataGrid ItemsSource="{Binding Items}">
  <DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Enabled}" Value="False">
          <Setter Property="IsEnabled" Value="False" />
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </DataGrid.RowStyle>
</DataGrid>

I'd like to prevent the disabled rows from being selected. In the above example, you can't select the disabled rows by clicking on them but there are other ways of selecting them, e.g., Ctrl-A selects all rows including the disabled ones, selecting an enabled row then shift-clicking another enabled row will also select any disabled rows between them, etc...

Is there a way to prevent the disabled rows from being selected at all? (So, for example, Ctrl-A would select only enabled rows)

Upvotes: 1

Views: 443

Answers (1)

AnjumSKhan
AnjumSKhan

Reputation: 9827

You have to handle the SelectedCellsChanged event of the DataGrid. In the example below, I have used list of Student objects with Enabled property.

private void Dgrd_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {          
            foreach(DataGridCellInfo info in e.AddedCells)
            {
                if (info.Item is Student && ((Student)info.Item).Enabled == false)                    
                    ((DataGridRow)Dgrd.ItemContainerGenerator.ContainerFromItem(info.Item)).IsSelected = false;                    
            }
        }

I have checked it , and it solves all the issues mentioned in your question.

Upvotes: 1

Related Questions