我正在尝试将选定的树视图节点复制到剪贴板,以便将其粘贴到记事本中。这是我的代码,但它不起作用。
TreeNode selNode = (TreeNode)this.treeView1.SelectedNode;
Clipboard.SetData("TreeNode", selNode);
答案 0 :(得分:16)
记事本对Winforms TreeNode类一无所知。改为使用Clipboard.SetText():
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;
}
}
答案 1 :(得分:2)
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; }
答案 2 :(得分:0)
如果您希望其他程序识别剪贴板上的内容,则需要使用可识别的数据格式(例如纯文本或位图)字符串参数,并将树节点格式化为该格式(例如,如果选择文本,你应该传递一个'字符串'作为剪贴板数据,也许是TreeNode.Text值)。有关不同的预定义类型,请参阅System.Windows.Forms.DataFormats。