7
votes

I want to be able to copy text from DataGrid Cell.

  1. First possible solution could be setting SelectionUnit to Cell but that's not an option for me since I need to select FullRow
  2. Second possible approach was to have DataGridTemplateColumn with readonly TextBox in it. But there is an issue with styles. My previous question: DatagridCell style overriden by TextBox style. I need really bright color for text in row, but really dark in selected row.
  3. Third is to set IsReadOnly="False" on DataGrid and provide EditingElementStylefor DataGridTextColumn

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

    But here comes a really terrible bug WPF Datagrid Text Column allows one character text enter when the internal text box is set to read only.

Do you know about some different solution for this? Or workaround? Thank you.

EDIT

I noticed that DataGrid from Extended WPF Toolkit doesn't have this bug, but it seems it has different structure and I wouldn't be able ty apply my DataGrid Style.

I noticed that using ReadOnly TextBox as EditingElementStyle of DataGridColumn brings further problems. When you use OneWay binding then it's not possible to get cell to Editing state. It's not acceptable to let the user override for example ID of some entity displayed in DataGrid. So it has to be somehow readonly or at least OneWay binding.

At this moment I have no solution for this at all. Is there any other way to let the user copy from cell while the row is selected and highlighted? Have I failed to notice some other solution? Thanks for reading.

1
is your Row an Object?WiiMaxx
@WiiMaxx DataGrid's ItemsSource is bound for example to ObservableCollection<Foo> and columns are based on properties of Foo In Column1 is Foo.Property1 and so on.Kapitán Mlíko
maybe this can help you msdn.microsoft.com/de-de/library/…WiiMaxx

1 Answers

2
votes

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

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

and in code-behind

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 gets executed everytime the selection changed in the data grid itself.