0

I m new to WPf Datagrid .My requirement if i select a cell in datagrid and press enter it should changed to readonly= false(editable) and user can change the content and again if he press enter key the cell should change to readonly = true(noneditable).

My xaml look like this:

<DataGrid AutoGenerateColumns="False" Height="496"  HorizontalAlignment="Left"  
          PreviewKeyDown="DgvMaterial_PreviewKeyDown" DataGridCell.Selected="DataGrid_select" 
          Name="DgvMaterial" VerticalAlignment="Top" Width="958" Margin="21,20,0,0"  
          ItemsSource="{Binding Path=., Mode=OneWay}"   
          AlternationCount="1" AlternatingRowBackground="#FFE9FFE9" 
          SelectionUnit="FullRow" CanUserResizeColumns="False" DataContext="{Binding}" 
          RowHeight="30" UseLayoutRounding="True" 
          RowHeaderWidth="0" OverridesDefaultStyle="False" ColumnHeaderHeight="30" 
          SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Auto" 
          FontFamily="MS Gothic" FontSize="12" CellStyle="{StaticResource Body_Content_DataGrid_Centering}" 
          IsHitTestVisible="True" SelectionChanged="DgvMaterial_SelectionChanged" 
          Loaded="DgvMaterial_Loaded" CellEditEnding="DgvMaterial_CellEditEnding" TabIndex="5"
          SelectedIndex="-1" IsReadOnly="True"> 
DHN
  • 4,807
  • 3
  • 31
  • 45
  • And the focus should remain in same cell – user1929251 Jun 03 '13 at 13:32
  • did you try to use `DataGridTemplateColumn` and specify `CellTemplate` for view (for example `TextBlock`) and `CellEditingTemplate` for edit (for example `TextBox`)? – dkozl Jun 03 '13 at 13:46

1 Answers1

2

Probably what you're looking for is DataGridTemplateColumn which can have 2 templates. One is to show value (DataGridTemplateColumn.CellTemplate) and the other is used in edit mode (DataGridTemplateColumn.CellEditingTemplate):

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=.}">
  <DataGrid.Columns>
      <DataGridTemplateColumn Header="Column">
          <DataGridTemplateColumn.CellEditingTemplate>
              <DataTemplate>
                  <TextBox Text="{Binding Path=ColumnName, UpdateSourceTrigger=PropertyChanged}"/>
              </DataTemplate>
          </DataGridTemplateColumn.CellEditingTemplate>
          <DataGridTemplateColumn.CellTemplate>
              <DataTemplate>
                  <TextBlock Text="{Binding Path=ColumnName}"/>
              </DataTemplate>
          </DataGridTemplateColumn.CellTemplate>
      </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

You can specify it per column, not for grid, and by default it will go into edit mode on F2 or double click but you can handle DataGrid.PreviewKeyDown and BeginEdit() on Enter

dkozl
  • 32,814
  • 8
  • 87
  • 89