I am trying to copy the selected treeview node to the clip board so I can paste it in notepad. Here is my code but it doesn't work.
TreeNode selNode = (TreeNode)this.treeView1.SelectedNode;
Clipboard.SetData("Tr开发者_开发百科eeNode", selNode);
Notepad doesn't know anything about the Winforms TreeNode class. Use Clipboard.SetText() instead:
private void treeView1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == (Keys.Control | Keys.C)) {
if (treeView1.SelectedNode != null) {
Clipboard.SetText(treeView1.SelectedNode.Text);
}
e.SuppressKeyPress = true;
}
}
XAML:
<TreeView> <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <EventSetter Event="Loaded" Handler="ItemLoaded"/> </Style > </TreeView.ItemContainerStyle> </TreeView>
C#:
protected void ItemLoaded(object sender, EventArgs e) { if (sender is TreeViewItem) { TreeViewItem item = sender as TreeViewItem; if (item.CommandBindings.Count == 0) { CommandBinding copyCmdBinding = new CommandBinding(); copyCmdBinding.Command = ApplicationCommands.Copy; copyCmdBinding.Executed += CopyCmdBinding_Executed; copyCmdBinding.CanExecute += CopyCmdBinding_CanExecute; item.CommandBindings.Add(copyCmdBinding); } } private void CopyCmdBinding_Executed(object sender, ExecutedRoutedEventArgs e) { if (sender is TreeViewItem) if ((sender as TreeViewItem).Header is MyClass) Clipboard.SetText(((sender as TreeViewItem).Header as MyClass).MyValue); } private void CopyCmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = false; if (sender is TreeViewItem) if ((sender as TreeViewItem).Header is MyClass) e.CanExecute = true; }
If you want other programs to recognise what's on the clipboard, you need to use a recognised data format (e.g. plain text, or bitmap) string parameter, and to format the tree node into that format (e.g. if you choose text, you should pass a 'string' as the clipboard data, perhaps the TreeNode.Text value). See System.Windows.Forms.DataFormats for the different predefined types.
精彩评论