WPF ListView's GridView copy to clipboard
I've a GridView like follow:
<ListView ItemsSource="{Binding Path=Foo, Mode=OneWay}">
<ListView.View>
<GridView>
<GridViewColumn Header="Full name"
DisplayMemberBinding="{Binding Path=FullName}" />
All I wish is that when pressing Ctrl + C 开发者_运维问答all items (or selected items) are copied to the clipboard. Currently it's not. I'm using WPF 3.0.
Partially answered by WPF listbox copy to clipboard but what I need seem simpler and I guess has also a simpler solution.
PS: This GridView doesn't support built-in column sorting and so on. If you know a better control that's free and support copying feel free to suggest it as a solution.
Took me some time to answer this question, so here's how I did it to save someone else time:
Function to copy the data to the clipboard, it also solves the problem of getting the rows in the right order in the resultant string:
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.");
}
}
}
I still have occasional issues with the a COMException when I copy stuff to the clipboard, hence the try-catch. I seem to have solved this (in a very bad and lazy fashion) by sort of clearing the clipboard, see below.
And to bind this to 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)
{ }
}
which is called from:
public MainWindow()
{
InitializeComponent();
add_copy_handle();
}
Obviously this is copied a lot from the link above, just simplified but I hope it's useful.
精彩评论