How can i use DatagridTextColumn.ElementStyle to Make DatagridTextColumn readonly?

1.4k views Asked by At

can i use elementStyle to bind DatagridTextColumn IsReadOnly to a Property inside a ViewModel(here IsReadOnlyProperty)? something like this:

  <DataGridTextColumn.ElementStyle>
      <Style TargetType="{x:Type TextBlock}">
          <Setter Property="IsEnabled" Value="{Binding IsReadOnlyProperty}"/>
      </Style>
  </DataGridTextColumn.ElementStyle>
  <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="{x:Type TextBlock}">
               <Setter Property="IsEnabled" Value="{Binding IsReadOnlyProperty}" />
        </Style>
  </DataGridTextColumn.EditingElementStyle>
1

There are 1 answers

0
Kacper Stachowski On

Try this:

<DataGridTextColumn IsReadOnly="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.IsReadOnlyProperty}" />

When you create DataGrid, you set its DataContext by assigning ItemsSource. This limits ALL controls inside DataGrid to only use objects from their parent DataContext, so if you want to bind to a property from outside of this DataContext, you have to explicitly declare that you want to change your scope.