编辑DataGridTemplateColumn的行为

时间:2017-06-01 11:23:58

标签: c# wpf datagrid datagridtemplatecolumn datagridtextcolumn

我的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中,双击将光标设置为单击的位置,或者如果在空格中单击,则选择单元格的完整内容
  • 开始输入不会进入编辑模式

有没有办法达到完全相同的行为?

1 个答案:

答案 0 :(得分:1)

您可以尝试从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" />