我知道这是一篇较旧的帖子,但此解决方案是为了完整性而发布的,并且缺少使用与 DataGridRowClipboardEventArgs 关联的合适的 DataGrid 事件方法签名。
Clipboard.SetText 可能很不稳定,不会一直抓取/设置剪贴板。
在名为 myDataGrid 的 dataGrid 的 SelectionUnit 模式下设置“FullRow”
<DataGrid x:Name="myDataGrid" SelectionUnit="FullRow"></DataGrid>
我们有一个 myDataGrid_CopyingRowClipboardContent 方法,它会为 dataGrid 中的每一行调用以将其内容复制到剪贴板。例如,对于一个有 7 行的数据网格,这被调用了 7 次。
public int clipboardcalledcnt { get; set; } //CopyingRowClipboardContent invoked count
private void myDataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
PathInfo cellpath = new PathInfo(); //a custom class to hold path info
string path = string.Empty;
DataGrid dgdataPaths = (DataGrid)sender;
int rowcnt = dgdataPaths.SelectedItems.Count;
cellpath = (PathInfo)e.Item;
path = "Row #"+ clipboardcalledcnt +" Len="+ cellpath.Length.ToString() + ", path=" + cellpath.Path;
e.ClipboardRowContent.Clear();
if (clipboardcalledcnt == 0) //add header to clipboard paste
e.ClipboardRowContent.Add(new DataGridClipboardCellContent("", null, "--- Clipboard Paste ---\t\t\n")); // \t cell divider, repeat (number of cells - 1)
clipboardcalledcnt++;
e.ClipboardRowContent.Add(new DataGridClipboardCellContent(path, null, path));
if (clipboardcalledcnt == rowcnt)
clipboardcalledcnt = 0;
}