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

Time:07-15

I am trying to set IsReadOnly in a DataGridTextColumn by binding it to a property. Sounds simple. Let's have a look:

<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?

Many thanks in advance for your time and effort reading and answering my question. :)

CodePudding user response:

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.

  • Related