Call this function on every TreeViewItem you want the copy command to work on
private void AddCopyCommand(ref TreeViewItem tvi)
{
CommandBinding copyCmdBinding = new CommandBinding();
copyCmdBinding.Command = ApplicationCommands.Copy;
copyCmdBinding.Executed += copyCmdBinding_Executed;
copyCmdBinding.CanExecute += copyCmdBinding_CanExecute;
tvi.CommandBindings.Add(copyCmdBinding);
}
Alternatively you could do this in xaml with:
<TreeViewItem>
<TreeViewItem.Commandbindings>
<CommandBinding Command="ApplicationCommands.Copy"
Executed="copyCmdBinding_Executed"
CanExecute="copyCmdBinding_CanExecute"/>
</TreeViewItem.CommandBindings
</TreeViewItem>
Then you have to write the functions to check for execution and actually execute:
private void copyCmdBinding_Executed (object sender, ExecutedRoutedEventArgs e) {
// Set text to clip board
TreeViewItem tvi = (TreeViewItem)sender;
Clipboard.SetText((String)tvi.Header);
}
private void copyCmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
//Check for text
TreeViewItem tvi = (TreeViewItem)sender;
if (tvi.Header != null)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
Note: This should work on any WPF Control, not just the TreeViewItem.