Sunday, September 4, 2016

Set DataGridTemplateColumn Control to ReadOnly in WPF

Hi all,
There was a question raised on how to set a control (ex. TextBox) inside the DataGridTemplateColumn of a WPF DataGrid to ReadOnly. The solution to that is to get the DataGridRow followed by accessing the DataGridCell and then get the VisualChild control inside the DataGridCell. By then, you can set the control's property IsReadOnly to true.
XAML Code
<DataGrid x:Name="dgPerson" Grid.Column="2" Grid.Row="2" CanUserDeleteRows="False" 
     AutoGenerateColumns="False" CanUserAddRows="False">
 <DataGrid.Columns>
  <DataGridTemplateColumn Header="ID" Width="150">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtID" Text="{Binding ID, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn Header="Name" Width="250">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtName" Text="{Binding Name, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
  <DataGridTemplateColumn Header="Department Code" Width="150">
   <DataGridTemplateColumn.CellTemplate>
    <DataTemplate >
     <TextBox Name="txtDept" Text="{Binding Department, Mode=OneWay}" />
    </DataTemplate>
   </DataGridTemplateColumn.CellTemplate>
  </DataGridTemplateColumn>
 </DataGrid.Columns>
</DataGrid>

VB.NET Code
Private Sub Window_Loaded_1(sender As Object, e As RoutedEventArgs)
        
 'set read only DataGridTemplateColumn (3rd column)
 SetReadOnlyDataTemplateColumn(2)
End Sub
 
Private Sub SetReadOnlyDataTemplateColumn(ByVal columnIndex As Integer)
 For index = 0 To dgPerson.Items.Count - 1 Step 1
  Dim txtSequence As TextBox
  Dim row As DataGridRow = dgPerson.GetRow(index)
  Dim sequenceColumn As DataGridCell = TryCast(dgPerson.Columns(columnIndex).GetCellContent(row).Parent, DataGridCell)
  txtSequence = DataGridExtensions.GetVisualChild(Of TextBox)(sequenceColumn)

  If txtSequence IsNot Nothing Then
   txtSequence.IsReadOnly = True
  End If
 Next
End Sub

Extension Methods WPF DataGrid Row and Cells Extension Methods.
Screenshot

0 comments:

Post a Comment