How to copy the value of a DataGrid cell to the clipboard

I have a DataGrid . But I want to get the targeted value of the cell in the CopyingRowClipboardContent event. But e.ClipboardRowContent returns me all the selected cell values ​​due to SelectionUnit . And I should not change the datagrid select box. To solve the problem, I need to get a targeted number of cell columns. Then I will remove all column values ​​from clipboarcContent . How can I focus a cell in the CopyingRowClipboardContent event?

+6
source share
4 answers

Improved version of Farhad's answer

 private void DataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e) { var currentCell = e.ClipboardRowContent[ dataGrid.CurrentCell.Column.DisplayIndex]; e.ClipboardRowContent.Clear(); e.ClipboardRowContent.Add( currentCell ); } 
+11
source

You can also use the following code to manage the contents of the clipboard.

 Clipboard.SetText("some value"); 
+4
source

I find a solution. First of all, I need the column number of the focused cell. I managed to get it using this code:

 DataGridResults.CurrentCell.Column.DisplayIndex; 

Then, in the CopyingRowClipboardContent event CopyingRowClipboardContent I have to delete all other column values.

 private void DataGridResults_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e) { int y = 0; for (int i = 0; i < e.EndColumnDisplayIndex; i++) { if (i != DataGridResults.CurrentCell.Column.DisplayIndex) { e.ClipboardRowContent.RemoveAt(i - y); y++; } } } 
+1
source

I found that this solution works for me on all DataGrids; even those that had hidden columns.

 // Clipboard Row content only includes entries for visible cells // Figure out the actual column we are looking for (taking into account hidden columns) int columnIndex = dataGrid.CurrentCell.Column.DisplayIndex; var column = dataGrid.Columns[columnIndex]; // Find the associated column we're interested in from the clipboard row content var cellContent = clipboardRowContent.Where(item => item.Column == column).First(); clipboardRowContent.Clear(); clipboardRowContent.Add(cellContent); 
+1
source

Source: https://habr.com/ru/post/925841/


All Articles