Search code examples
wpfwpfdatagridlost-focus

Gotfocus and lostfocus on dataGridTextColumn not possible


I've got this WPF DataGrid:

<DataGrid ItemsSource="{DynamicResource TNMaps}"  RowHeaderWidth="0" Width="680" AutoGenerateColumns="False" RowHeight="35" SelectionUnit="Cell"  >
     <DataGrid.Columns>
          <DataGridTextColumn Header="Test Name" Width="2*" Binding="{Binding TestName}" IsReadOnly="True" FontSize="20"/>
          <DataGridTextColumn Header="LIS Name" Width="*" Binding="{Binding LISName}"  FontSize="20" />
     </DataGrid.Columns> 
     <DataGrid.ColumnHeaderStyle>
          <Style TargetType="DataGridColumnHeader">
               <Setter Property="FontSize" Value="20"/>
          </Style>
     </DataGrid.ColumnHeaderStyle>
</DataGrid>

The user can edit the cells in the dataGridTextcolumn with Headername "LIS Name". I've tried to set a gotfocus and a lostfocus event on this datagridTextColumn, but these events aren't available. I need to do this so i can display a keyboard when the user tries to edit a cell in this column (for touch versions).

Is there another way how I can do this?


Solution

  • When you need more refined control over cell vs. cell in edit, setting focus, etc, instead of using DataGridTextColumn, I would suggest use DataGridTemplateColumns and define cell and editing cell tempplates:

    <DataGrid ItemsSource="{DynamicResource TNMaps}"  RowHeaderWidth="0" Width="680" AutoGenerateColumns="False" RowHeight="35" SelectionUnit="Cell"  >
     <DataGrid.Columns>
        <DataGridTemplateColumn>           
             <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                            <TextBlock Text="{Binding TestName}" GotFocus="OnCellGotFocus"/>
                      </DataTemplate>
             </DataGridTemplateColumn.CellTemplate>
             <DataGridTemplateColumn.CellEditingTemplate>
                  <DataTemplate>
                    <TextBox Text="{Binding TestName}"  GotFocus="OnCellInEditGotFocus"/>
                  </DataTemplate>
              </DataGridTemplateColumn.CellEditingTemplate>
         </DataGridTemplateColumn>
    

    In put TextBlock vs TextBox, but you can do whatever, and get full control that the visual element offers. You can also force the grid to get into EditMode and showthe editing template on line selection, keydown, etc..etc..