3

我最近开始将 WPF Datagrid 与包含 WPF AutoCompleteBox 的 DataGridTemplateColumns 一起使用,但在为这些 DataGridTemplateColumns 实现 Clipboard.Paste 功能时遇到了麻烦。

我已经设法通过 Vishal的指南让 Clipboard.Paste 与内置 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();

    }

}

谢谢!

4

3 回答 3

1

使用 ClipboardContentBinding 并将绑定的模式设置为 TwoWay,似乎可行。

GetBindingExpression 然后返回非空值(ClipboardContentBinding 上的绑定),并且 UpdateSource 不会失败。

我想这个解决方案仅限于您在源上触发了 PropertyChanged 事件的情况,这反过来又更新了列的 DataTemplate 中的控件。

于 2011-10-10T02:09:51.570 回答
0

This is because for DataGridTemplateColumns there isnt a binding. The binding is taken care of in your datatemplate. The cell datatemplate just gets the item (the item in the row) and binds to it. there is no way for the column to know what is in the cell.

I have worked around this by creating my own columns. I derive from DataGridTextColumn (if i am doing one that has text input) and override the GenerateElement and GenerateEditingElement.

This way i still have the binding property that can be used for pasting.

于 2010-04-12T23:21:44.717 回答
0

如图使用ClipboardContentBinding

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

取自这里

于 2010-09-23T20:22:33.353 回答