C#C
C#3y ago
Thalnos

✅ Copy value of DataGridCell to clipboard in WPF app

when you select a DataGridCell in a DataGrid from WPF and try to copy its value using ctrl + c keys the default behaviour is to copy the whole row rather than the focused cell's value, which me and my team find to be very weird so we wanna change this behaviour.
I'm not sure why it isn't working and I don't know how to further debug this issue, so I appreciate any help.
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
        {
            var dataGrid = sender as DataGrid;
            if (Keyboard.Modifiers == ModifierKeys.Control && e.Key == Key.C) //ctrl + c got pressed
            {
                var currentCell = dataGrid.CurrentCell; // cell that currently has focus
                var content = currentCell.Column.GetCellContent(currentCell.Item) as TextBlock;
                var text = content.Text; //text contains "test"
                Clipboard.SetText(content.Text); //clipboard contains "test test" for some reason rather than "test"
            }
        }

on the image you can see a snippet of what the DataGrid looks like. When I select either of those cells and press ctrl + c, the
text
variable holds the expected value of "test" but somehow the clipboard text still ends up being "test test" instead (the whole row) and I don't understand what's going on here
image.png
Was this page helpful?