Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable specific DataGridCheckBoxColumn cells via ViewModel

Tags:

mvvm

wpf

datagrid

My MVVM project has this ViewModel:

class ListViewModel : ViewModelBase {
    public ObservableCollection<ListItemviewModel> Items { ... }
}
class ListItemViewModel : ViewModelBase {
    public String  Name      { ... }
    public Boolean IsChecked { ... }
    public Boolean IsEnabled { ... }
}

Writing the XAML seemed straightforward:

<DataGrid ItemsSource="{Binding Items}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn     Header="Name"       Binding="{Binding Name}" />
        <DataGridCheckBoxColumn Header="Is checked" Binding="{Binding IsChecked}" />
</DataGrid>

However, how can I get it so when a ListItemViewModel's IsEnabled property is false the DataGridCheckBoxColumn's cell in that row is disabled?

I tried setting IsReadOnly={Binding IsDisabled} (and adding an IsDisabled property to ListItemViewModel, however to no avail) - and I recognise that would disable/enable the whole column, not individual cells.

I also tried these instructions ( How to disable a cell in a DataGrid while binding to an ObservableCollection ):

<DataGridCheckBoxColumn Header="Is checked" Binding="{Binding IsChecked}" />
    <DataGridCheckBoxColumn.CellStyle>
        <Style TargetType="DataGridCell">
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsEnabled}" Value="False">
                    <Setter Property="IsEnabled" Value="False" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridCheckBoxColumn.CellStyle>

However this has no effect and no binding errors are displayed in the Output window.

like image 741
Dai Avatar asked Oct 27 '15 11:10

Dai


1 Answers

It turns out the question I linked to ( How to disable a cell in a DataGrid while binding to an ObservableCollection ) was almost-right, but the XAML was somewhat cargo-cultish. The correct XAML is merely:

<DataGridCheckBoxColumn.CellStyle>
    <Style TargetType="DataGridCell">
        <Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
    </Style>
</DataGridCheckBoxColumn.CellStyle>

Sorted!

like image 176
Dai Avatar answered Sep 21 '22 04:09

Dai