我花了一些时间来回答这个问题,所以我是这样做来节省别人时间的:
将数据复制到剪贴板的功能,它还解决了在结果字符串中按正确顺序获取行的问题:
void copy_selected()
{
if (listview.SelectedItems.Count != 0)
{
//where MyType is a custom datatype and the listview is bound to a
//List<MyType> called original_list_bound_to_the_listview
List<MyType> selected = new List<MyType>();
var sb = new StringBuilder();
foreach(MyType s in listview.SelectedItems)
selected.Add(s);
foreach(MyType s in original_list_bound_to_the_listview)
if (selected.Contains(s))
sb.AppendLine(s.ToString());//or whatever format you want
try
{
System.Windows.Clipboard.SetData(DataFormats.Text, sb.ToString());
}
catch (COMException)
{
MessageBox.Show("Sorry, unable to copy surveys to the clipboard. Try again.");
}
}
}
当我将内容复制到剪贴板时,我仍然偶尔会遇到 COMException 问题,因此是 try-catch。我似乎通过清除剪贴板解决了这个问题(以一种非常糟糕和懒惰的方式),见下文。
并将其绑定到 Ctrl + C
void add_copy_handle()
{
ExecutedRoutedEventHandler handler = (sender_, arg_) => { copy_selected(); };
var command = new RoutedCommand("Copy", typeof(GridView));
command.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Control, "Copy"));
listview.CommandBindings.Add(new CommandBinding(command, handler));
try
{ System.Windows.Clipboard.SetData(DataFormats.Text, ""); }
catch (COMException)
{ }
}
调用自:
public MainWindow()
{
InitializeComponent();
add_copy_handle();
}
显然这是从上面的链接中复制了很多,只是简化了,但我希望它有用。