✅ 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"
}
}
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
4 Replies
HimmDawg
HimmDawg2y ago
You need to use e.Handled = true at the end or else the DataGrid will just perform it's own default actions (which in this case is copy the entire row)
Florian Voß
Florian VoßOP2y ago
that works, thank you very much. May i ask how I could've found that out? I was stuck on this for quite some time I made research and also asked chat gpt but nowhere e.Handled got mentioned
HimmDawg
HimmDawg2y ago
At my workplace, I work with .NET Framework unfortunately and there are a lot events where the same call must be made to prevent the default behaviour. Those events also are passed KeyEventArgs. Idk if ChatGPT already searches the web, but if not, try to use Phind. It looks a little cluttered lately but it can search the web for you and asks you questions to confirm its findings + it shows the used sources
Florian Voß
Florian VoßOP2y ago
ah so its generally a common technique to avoid other handlers from executing by setting the event to Handled, I see tyvm. I'll keep this in mind Chat GPT does search the web and it can also give sources, at least the one that's integrated into Bing. But I'll have a look on this Phind, ty
Want results from more Discord servers?
Add your server