Tuesday, February 14, 2017

Copy WPF DataGrid selected rows to clipboard using CopyingRowClipboardContent

Searched high-and-low for this code that properly used of a DataGrid event method signature associated with the DataGridRowClipboardEventArgs. Clipboard.SetText can be flaky, not grabbing/setting the clipboard all the time. 

Set "FullRow" at the SelectionUnit mode for dataGrid called myDataGrid

1
<DataGrid x:Name="myDataGrid" SelectionUnit="FullRow"></DataGrid>

We have a method myDataGrid_CopyingRowClipboardContent that gets called for each row in the dataGrid to copy its contents to the clipboard. For example,for a datagrid with 10 rows this is called 10 times.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;

}

No comments:

Post a Comment