Copy TreeView Node

后端 未结 3 2081
离开以前
离开以前 2021-01-19 15:21

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 = (         


        
相关标签:
3条回答
  • 2021-01-19 15:41

    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;
    }
    
    0 讨论(0)
  • 2021-01-19 15:59

    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.

    0 讨论(0)
  • 2021-01-19 16:05

    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;
            }
        }
    
    0 讨论(0)
提交回复
热议问题