Florian
Florian

Reputation: 1887

DataGrid set single cells readonly

I am looking for a way to disable some of my cells in a WPF DataGrid. Since isReadOnly is not a DependencyProperty, I can not use it.

Is there any other way to do this?

I would like to write something like this:

<DataGridTextColumn IsReadOnly="{Binding Path=Value,Converter={StaticResource ValueToBooleanConverter}}" /> 

but any way how to do this would be nice, since I don't see a way, but Splitting the data in different DataGrid's.

Upvotes: 1

Views: 2292

Answers (2)

Maxence
Maxence

Reputation: 13329

You can use the DataGrid.OnBeginningEdit event:

void DataGrid_OnBeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
    DataGridRow row = e.Row;
    var viewModel = (YourViewModel) row.Item;
    if (<Test to check if it is the expected column> 
      && viewModel.Value == <?>) e.Cancel = true;
}

This does not break MVVM. The behavior is driven by a property of your view model (something you can test) and there is only basic code to bind the property to the view.

Upvotes: 0

icebat
icebat

Reputation: 4774

If you can`t make a column read-only, you can go to a cell level. For example by making Style and adding it to required columns:

 <DataGridTextColumn Binding="{Binding TextProperty}">
      <DataGridTextColumn.CellStyle>
           <Style TargetType="DataGridCell">
               <Setter Property="IsEnabled" 
                       Value="{Binding Path=Value,Converter={StaticResource ValueToBooleanConverter}}" />
           </Style>
       </DataGridTextColumn.CellStyle>
 </DataGridTextColumn>

I made the Style inside column here but of cource it can be moved to resources and referenced in any required columns by key (but you gotta be shure converter is accessible for that style). Cell`s IsReadOnly doesn`t seem to have a setter so I`m using IsEnabled here which is doing the job quite nicely.

Upvotes: 3

Related Questions