Copy a ListView’s Items to the Clipboard

Posted on March 10, 2009. Filed under: WPF | Tags: , , |

How can you copy the selected rows of a ListView to the clipboard? With the use of attached properties, this is an easy task that doesn’t require any custom controls or code-behind files. Here’s how:
The XAML

The XAML

First we need to extract the selected items from the ListView. This can be done by iterating over the SelectedItems collection and applying the bindings, which we can find in the Columns collection, to each object. That allows us to use format strings and converters which have been declared in the XAML. For each selected item, we append a line to the result.

csvsample1.png

Click the button or press ctrl+c

Then we need to wrap this in an attached property. This approach is similar to what Michael Brown used to sort a grid. When the attached property is registered, we add a command binding for the copy-command to the listview’s command bindings.

Result, pasted from the clipboard

Result, pasted from the clipboard

When the command is executed, we just call the extension method on the listview and copy the result to the clipboard. There are three more attached properties you can use to set the delimiter, the quotation marks and whether or not to include the headers in the output.

Sourcecode

Make a Comment

Leave a comment

3 Responses to “Copy a ListView’s Items to the Clipboard”

RSS Feed for Jann’s Blog Comments RSS Feed

Howdy, and nice to see your first post!
Yesterday I finished setting up my IDE (after several ours of fighting bugs) and am right now getting familiar with all the XAML I knew so far more or less superficially. Perhaps your blog will be a good source for inspiration … 🙂
Anyway you’ll definitely need to go over the formatting of your post; at the moment everything looks a bit shaken and tangled, pictures floating around at random positions …

Thanks! I changed the formatting of the pictures. It looks better now

Hallo Jännchen!


Where's The Comment Form?

Liked it here?
Why not try sites on the blogroll...