C# 使用DataGridTemplateColumns粘贴WPF DataGrid的功能

C# 使用DataGridTemplateColumns粘贴WPF DataGrid的功能,c#,wpf,wpfdatagrid,C#,Wpf,Wpfdatagrid,我最近开始将WPF Datagrid与包含WPF自动完成框的DataGridTemplateColumns一起使用,但在实现这些DataGridTemplateColumns的Clipboard.Paste功能时遇到了问题 我已经通过Vishal的指南获得了剪贴板。粘贴使用内置的DataGridColumns,但它不适用于DataGridTemplateColumns 深入研究DataGridColumn类中的OnPastingCellClipboardContent方法,fe.GetBindi

我最近开始将WPF Datagrid与包含WPF自动完成框的DataGridTemplateColumns一起使用,但在实现这些DataGridTemplateColumns的Clipboard.Paste功能时遇到了问题

我已经通过Vishal的指南获得了剪贴板。粘贴使用内置的DataGridColumns,但它不适用于DataGridTemplateColumns

深入研究DataGridColumn类中的OnPastingCellClipboardContent方法,fe.GetBindingExpression(CellValueProperty)似乎返回null,而不是所需的BindingExpression

谁能给我指一下正确的方向吗

public virtual void OnPastingCellClipboardContent(object item, object cellContent)
    {
        BindingBase binding = ClipboardContentBinding;
        if (binding != null)
        {
            // Raise the event to give a chance for external listeners to modify the cell content
            // before it gets stored into the cell
            if (PastingCellClipboardContent != null)
            {
                DataGridCellClipboardEventArgs args = new DataGridCellClipboardEventArgs(item, this, cellContent);
                PastingCellClipboardContent(this, args);
                cellContent = args.Content;
            }

            // Event handlers can cancel Paste of a cell by setting its content to null
            if (cellContent != null)
            {
                FrameworkElement fe = new FrameworkElement();
                fe.DataContext = item;
                fe.SetBinding(CellValueProperty, binding);
                fe.SetValue(CellValueProperty, cellContent);

                BindingExpression be = fe.GetBindingExpression(CellValueProperty);

        be.UpdateSource();

    }

}

谢谢

这是因为DataGridTemplateColumns没有绑定。绑定在datatemplate中处理。cell datatemplate只获取项(行中的项)并绑定到它。列无法知道单元格中的内容

我通过创建自己的专栏来解决这个问题。我从DataGridTextColumn派生(如果我正在做一个有文本输入的列),并重写GenerateElement和GenerateEditingElement


这样,我仍然具有可用于粘贴的绑定属性。

使用
ClipboardContentBinding
,如图所示:

<DataGridTemplateColumn 
    Header="First Name" 
    SortMemberPath="FirstName" 
    ClipboardContentBinding="{Binding FirstName}" 
    >
    <DatGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding FirstName}" />
        </DataTemplate>
    </DatGridTemplateColumn.CellTemplate>
    <DataGridTemplateColumn.CellEditingTemplate>
        ...
    </DataGridTemplateColumn>
</DataGridTemplateColumn>

...

摘自。

使用ClipboardContentBinding并将绑定模式设置为双向,似乎可以工作

GetBindingExpression然后返回非null的内容(ClipboardContentBinding上的绑定),并且UpdateSource不会失败


我认为此解决方案仅限于在源上触发PropertyChanged事件的情况,该事件反过来会更新列的DataTemplate中的控件。

这不适用于WPFToolkit 2010年2月的版本,也可能不适用于其他版本。这是在某处记录的,还是您通过测试发现的
ClipboardContentBinding
作为属性存在于中,我知道它存在,并且我已将错误跟踪到OP。如果仔细查看OP发布的代码,您会发现尽管正在使用ClipboardContentBinding,但它将失败。我已经通过反射编写了一个变通方法,因为我不想创建自定义列。简而言之:不,不适用于WPFToolkit的模板列。不过,我不知道.NET4的WPF。