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;

}

2 comments:

  1. ///
    /// Hold info about path
    ///
    public class PathInfo {

    public PathInfo()
    {
    isDir = false;
    }
    public string ReplacementPath { get; set; }

    public string Path { get; set; }

    public int Length { get; set; }


    public int ShortLength { get; set; }

    public int RowCount { get; set; }

    //Set abbreviate path suggestion
    public string AbbrvPath { get; set; }

    public bool isDir { get; set; }

    public bool isShortened { get; set; }

    public string _abpath { get; set; }


    }

    ReplyDelete