DataGridTemplateColumn 的编辑行为

Edit behaviour of DataGridTemplateColumn

我的 DataGrid 有几个 DataGridTemplateColumn 是这样的:

 <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>

DataGridSyntaxColumn只是为了设置焦点:

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

这工作正常,但编辑模式不像往常那样运行 DataGridTextColumn

例如:

有没有办法实现完全相同的行为?

您可以尝试从 DataGridTextColumn 继承并简单地覆盖 GenerateElement 方法:

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" />