我正在尝试将选定的树形节点复制到剪贴板,以便在记事本中粘贴。这是我的代码,但它不起作用。
TreeNode selNode = (TreeNode)this.treeView1.SelectedNode;
Clipboard.SetData("TreeNode", selNode);
记事本无法识别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;
}
}
<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;
}