Copy TreeView Node

2019-02-27 08:29发布

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("TreeNode", selNode);

3条回答
Bombasti
2楼-- · 2019-02-27 08:38

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.

查看更多
戒情不戒烟
3楼-- · 2019-02-27 08:49

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;
        }
    }
查看更多
走好不送
4楼-- · 2019-02-27 08:53

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;
}
查看更多
登录 后发表回答