Tuesday, February 14, 2017

Copy WPF DataGrid selected rows to clipboard using CopyingRowClipboardContent

Searchedhigh and low for this code, that properly use the e.ClipboardRowContent to copy C# .NET 4.0+ WPF DataGrid  selected rows to clipboard.

For my needs, I'm re-pasting back into the e.ClipboardRowContent the row I would like. The cell.Item is all the information I need for each selected row.

Hint: I was getting duplicates without doing an e.ClipboardRowContent.Clear(); after using the e.ClipboardRowContent . I was clearing before and using DataGrid.SelectedItems to build the rows. 

 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
private void yourDataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
 var dataGridClipboardCellContent = new List<DataGridClipboardCellContent>(); 
 
 string prevCell = "";
 string curCell = ""; 
 
 foreach (DataGridClipboardCellContent cell in e.ClipboardRowContent)
 {
  //Gives you access item.Item or item.Content here
        //if you are using your struct (data type) you can recast it here curItem = (yourdatatype)item.Item;  
  curItem = cell.Item.ToString(); 
  
  if (curCell != prevCell)
   dataGridClipboardCellContent.Add(new DataGridClipboardCellContent(item, item.Column, curCell)); 

  prevCell = curCell;  

 }
 e.ClipboardRowContent.Clear();
 
 //Re-paste back into e.ClipboardRowContent, additionally if you have modified/formatted rows to your liking
 e.ClipboardRowContent.AddRange(dataGridClipboardCellContent);

}


This a more general case


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
private void dataPaths_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)
{
   IList<DataGridCellInfo> cells = (sender as DataGrid).SelectedCells;

   foreach (DataGridCellInfo cell in cells)
       e.ClipboardRowContent.Add(new DataGridClipboardCellContent(e.Item, cell.Column, null));

   //or write out to a log
   foreach (var row in e.ClipboardRowContent)
      Console.WriteLine(row.Item.toString()); 
}

No comments:

Post a Comment