Chris
Chris

Reputation: 60

WPF: DataGridColumn loses DataContext when trying to bind a property to IsReadOnly

I am trying to set IsReadOnly in a DataGridTextColumn by binding it to a property. Sounds simple.

<DataGridTextColumn x:Name="NameColumn" Header="Name" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="{Binding IsLocked}" />

The main binding to the Name property of my ViewModel works fine. But the binding in IsReadOnly fails because the DataContext is null. But why? Name and IsLocked are on the same level in my ViewModel, and a few lines later IsLocked is used to display an icon by toggling visibility.

<DataGrid.Columns>

    <DataGridTextColumn x:Name="NameColumn" Header="Name" Binding="{Binding Name, UpdateSourceTrigger=PropertyChanged}" IsReadOnly="{Binding IsLocked}" />

    <materialDesign:DataGridComboBoxColumn
        Header="Produktart" IsReadOnly="{Binding IsLocked, UpdateSourceTrigger=PropertyChanged}"
        IsEditable="True"
        Width="100"
        SelectedValueBinding="{Binding ProductType, UpdateSourceTrigger=PropertyChanged}"   
        ItemsSourceBinding="{Binding ProducerTypesValues, UpdateSourceTrigger=PropertyChanged }" />
                
    <DataGridTemplateColumn Header="In Benutzung" IsReadOnly="true">
        <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Grid HorizontalAlignment="Center">
                            <materialDesign:PackIcon Kind="Lock" x:Name="lockIcon" Visibility="{Binding IsLocked, Converter={StaticResource VisibilityConverter }}" />
                    </Grid>
               </DataTemplate>
        </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

</DataGrid.Columns>

What can I do to set the binding in IsReadOnly correctly?

Upvotes: 0

Views: 156

Answers (1)

mm8
mm8

Reputation: 169240

But why?

Because the DataGridTextColumn is not part of the visual tree and doesn't inherit any DataContext.

The solution to get this working is to use a Freezable that captures the DataContext as explained and exemplified here.

Upvotes: 1

Related Questions