I have successfully used a few custom commands using MVVM-Light, but I want my application to respond to the standard ApplicationCommands, not just at a Window level, but at a detailed item level as well.
I have a TreeView
that I want to be able to copy and paste nodes in. Each TreeViewItem has its own ViewModel, and they are displayed via HierarchicalDataTemplates
in XAML as there are several different types. I have implemented methods to copy, paste, as well as CanCopy and CanPaste on my ViewModel classes. If appropriate, I could implement MVVM-Light RelayCommands pointing to these easily enough, but that doesn't seem right.
I would like to access the commands using a menu, Ctrl+C and Ctrl+V, or eventually a context menu. I also don't want to break copy/paste functionality for other elements in my UI, such as TextBoxes. It seems appropriate to use the built-in ApplicationCommands for this purpose. However, I am only seeing examples of these being handled in a UserControl code-behind. I don't have (or otherwise need) a UserControl, nor is that really following MVVM.
Is there a way I can bind ApplicationCommand.Copy
and ApplicationCommand.Paste
commands to my ViewModels, i.e., in the data templates?
I believe that you are looking for
CommandBindings
. I use something similar for some textboxes:Note that
PreviewCanExecute
andPreviewExecuted
are also available.Edit: Check out the sample here to make it MVVM compliant.
I have resolved this using Behaviors attached to the TreeView. The TreeViewItems or Templates to not seem to get the commands routed to them. Fortunately, the TreeView also has a SelectedItem property that can be used to get the ViewModel!
(Behaviors are conceptually similar to the solution in the link in @Natxo's answer, but it doesn't resolve everything.)
The Behavior class:
The XAML