我最近开始使用包含WPF AutoCompleteBox的DataGridTemplateColumns的WPF Datagrid,但是我在为这些DataGridTemplateColumns实现Clipboard.Paste功能时遇到了麻烦。
我设法让Clipboard.Paste通过Vishal的指南here使用内置的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();
}
}
谢谢!
答案 0 :(得分:1)
使用ClipboardContentBinding并将绑定的Mode设置为TwoWay,似乎有效。
GetBindingExpression然后返回非空的东西(ClipboardContentBinding上的绑定),UpdateSource不会失败。
我认为这个解决方案仅限于在源上触发PropertyChanged事件的情况,该事件反过来更新列的DataTemplate中的控件。
答案 1 :(得分:0)
这是因为DataGridTemplateColumns没有绑定。绑定在您的datatemplate中处理。单元格datatemplate只获取项目(行中的项目)并绑定到它。列无法知道单元格中的内容。
我通过创建自己的列来解决这个问题。我派生自DataGridTextColumn(如果我正在做一个有文本输入的那个)并覆盖GenerateElement和GenerateEditingElement。
这样我仍然可以使用绑定属性进行粘贴。
答案 2 :(得分:0)
有关创建自定义列的信息,请参阅此链接。
答案 3 :(得分: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>
取自here。