Search code examples
c#wpfdatagriddatagridtemplatecolumndatagridtextcolumn

Edit behaviour of DataGridTemplateColumn


my DataGrid has a few DataGridTemplateColumn's like this:

 <local:DataGridSyntaxColumn MinWidth="100" x:Name="cVariantNew1" Width="250">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <local:SyntaxTextBlock HorizontalAlignment="Left" SyntaxType="VARIANT" Value="{Binding Variants[0].Name, Mode=OneWay}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>

                    <DataGridTemplateColumn.CellEditingTemplate>
                        <DataTemplate>
                            <TextBox Text="{Binding Variants[0].Name, Mode=TwoWay, UpdateSourceTrigger=LostFocus}"  Style="{StaticResource GridTextBox}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellEditingTemplate>
</local:DataGridSyntaxColumn>

The DataGridSyntaxColumn ist just to set the focus:

 public class DataGridSyntaxColumn : DataGridTemplateColumn
    {
        protected override object PrepareCellForEdit(FrameworkElement editingElement,
                                                RoutedEventArgs editingEventArgs)
        {
            editingElement.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
            return base.PrepareCellForEdit(editingElement, editingEventArgs);
        }
    }

This is working fine, but the editing mode does not behave like the usual DataGridTextColumn

For example:

  • In DataGridTextColumn a doubleclick sets the cursor to the clicked position or if clicked in white space it selects the full content of the cell
  • Start typing does not enter edit mode

Is there a way to achieve the exact same behaviour?


Solution

  • You could try to inherit from DataGridTextColumn and simply override the GenerateElement method:

    public class DataGridSyntaxColumn : DataGridTextColumn
    {
        protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem)
        {
            SyntaxTextBlock textBlock = new SyntaxTextBlock()
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                SyntaxType = VARIANT
            };
    
            BindingBase binding = Binding;
            if (binding != null)
                BindingOperations.SetBinding(textBlock, TextBlock.TextProperty, binding);
            else
                BindingOperations.ClearBinding(textBlock, TextBlock.TextProperty);
    
            return textBlock;
        }
    }
    

    <local:DataGridSyntaxColumn MinWidth="100" Binding="{Binding Variants[0].Name}"  Width="250" />