wpf 复制到粘贴板,WPF列表框复制到剪贴板

I am trying to copy a standard WPF listbox selected Item (displayed) text to clipboard on CTRL+C. Is there any simple way to achieve this. If it is something that works for all the listboxes int he app.. that would be great.

Thanks in advance.

解决方案

As you're in WPF so you could try the attached behaviours

First you need a class like this:

public static class ListBoxBehaviour

{

public static readonly DependencyProperty AutoCopyProperty = DependencyProperty.RegisterAttached("AutoCopy",

typeof(bool), typeof(ListBoxBehaviour), new UIPropertyMetadata(AutoCopyChanged));

public static bool GetAutoCopy(DependencyObject obj_)

{

return (bool) obj_.GetValue(AutoCopyProperty);

}

public static void SetAutoCopy(DependencyObject obj_, bool value_)

{

obj_.SetValue(AutoCopyProperty, value_);

}

private static void AutoCopyChanged(DependencyObject obj_, DependencyPropertyChangedEventArgs e_)

{

var listBox = obj_ as ListBox;

if (listBox != null)

{

if ((bool)e_.NewValue)

{

ExecutedRoutedEventHandler handler =

(sender_, arg_) =>

{

if (listBox.SelectedItem != null)

{

//Copy what ever your want here

Clipboard.SetDataObject(listBox.SelectedItem.ToString());

}

};

var command = new RoutedCommand("Copy", typeof (ListBox));

command.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Control, "Copy"));

listBox.CommandBindings.Add(new CommandBinding(command, handler));

}

}

}

}

Then you have the XAML like this

Updates: For the simplest case, you can access the text in the below way:

private static string GetListBoxItemText(ListBox listBox_, object item_)

{

var listBoxItem = listBox_.ItemContainerGenerator.ContainerFromItem(item_)

as ListBoxItem;

if (listBoxItem != null)

{

var textBlock = FindChild(listBoxItem);

if (textBlock != null)

{

return textBlock.Text;

}

}

return null;

}

GetListBoxItemText(myListbox, myListbox.SelectedItem)

FindChild is a function to find a child of type T of a DependencyObject

But just like the ListBoxItem could be bound to object, the ItemTemplate could be different as well, so you can't rely on it in real projects.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值