DataGrid: Copy-ok, Paste-can do, Cut-how?

Sep 3, 2009 at 9:50 PM
Edited Sep 3, 2009 at 11:11 PM

I have "Copy" and "Paste" working just fine in my DataGrid project.  But how can I implement the "Cut" functionality?

The first part of implementing "Cut", is to copy the selected cells content to the clipboard.  So, I could use (i.e. inherit) the built-in Copy functionality for that in principle - but how practically?.  And for the second part: erasing the copied cells, I could use the code I already have made for pasting (derived from vinsibals posts).

I would appreciate a few pointers/ideas of how to make this work - or maybe there are other easier/better ways to do this? - or maybe it is very easy and I just cannot see how to?

Another factor is that cut, copy and paste already is built into WPF for many controls, e.g. the TextBox.  So, when you select the given text string (or a part of the text string) in a TextBox in the usual Windows way via the keyboard and/or the mouse, you automatically have a Context Menu available (right click) where Cut and Copy are enabled.  And when nothing is selected, Cut and Copy are nicely disabled and Paste is enabled.  

The complicating aspect of this existing functionality is that the same Context Menu mechanism is available for the cells in a DataGrid - but only Copy works, by design.   I will have to be able to control this context menu (or get rid of it), so Cut links up with my Cut implementation, and likewise for Paste but leaves Copy as it is.  How can I do that?

Regards, Fin

Coordinator
Sep 4, 2009 at 9:56 PM

Hi,

For your first question, you can use the copy command to get the content into the Clipboard.  Then you can use the dataGrid.SelectedCells property and clear the respective cell content.

For your second question, in order to get the Cut and Paste Routed UI Commands for the DataGrid, you need to implement your own commands as follows,

<DataGrid ...>
  <DataGrid.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Cut"   
      CanExecute="OnCanCutExecute" Executed="OnCutExecute"/>

... and just implement the OnCanCutExecute and OnCutExecute.  You may look at the link below for an example.

http://msdn.microsoft.com/en-us/magazine/cc785480.aspx

Hope that helps,

Saied Khanahmadi