Copy text from DataGrid cell

I want to be able to copy text from a DataGrid cell.

  • The first possible solution would be to install SelectionUnit in Cell , but this is not an option for me, since I need to select FullRow
  • The second possible approach was to have a DataGridTemplateColumn with readonly TextBox in it. But there is a problem with the styles. My previous question: DatagridCell style overridden by TextBox style . I need a really bright color for the text in the line, but in fact it is dark in the selected line.
  • Thirdly, you need to set IsReadOnly = "False" in the DataGrid and provide EditingElementStyle for the DataGridTextColumn

     <Style x:Key="EditingStyle" TargetType="{x:Type TextBox}"> <Setter Property="IsReadOnly" Value="True"/> </Style> ... <DataGridTextColumn ... EditingElementStyle="{DynamicResource EditingStyle}"/> 

    But here's a really terrible mistake. The WPF Datagrid text column allows you to enter one character text when the internal text box is set to read-only.

Do you know of any other solution? Or a workaround? Thanks.

EDIT

I noticed that the DataGrid from the Extended WPF Toolkit does not have this error , but it seems to have a different structure, and I could not apply my DataGrid style.

I noticed that using ReadOnly TextBox as EditingElementStyle in a DataGridColumn creates additional problems. When you use OneWay binding, then it is not possible to get a cell in Edit Status . It is not allowed for the user to override, for example, the ID of any object displayed in the DataGrid. Therefore, it should be somehow read-only, or at least OneWay binding .

At the moment, I have no solution for this. Is there any other way to allow the user to copy from a cell when a row is selected and selected? Have I really noticed another solution? Thanks for reading.

+4
source share
1 answer

You can do something dirty to get the current cell. In your xaml just add

 <DataGrid GotFocus="DataGrid_GotFocus" KeyDown="DataGrid_KeyDown"> 

and encoded

 private void DataGrid_GotFocus(object sender, RoutedEventArgs e) { if(e.OriginalSource is DataGridCell) _currentCell = (DataGridCell) e.OriginalSource; } private void DataGrid_KeyDown(object sender, KeyEventArgs e) { if(e.Key == Key.C && (e.SystemKey == Key.LeftCtrl || e.SystemKey == Key.RightCtrl)) { //Transform content here, like Clipboard.SetText(_currentCell.Content); } } 

This should do it because GotFocus is executed every time the selection changes in the data grid itself.

+1
source

All Articles