how can I copy the selected items in a WPF's ListView with binding to db fields to the Clipboard?
thank you Cristian
Since you want what is being displayed as opposed to the data on your class's properties you will need to grab the data from the controls directly.
var sb = new StringBuilder();
foreach(var item in this.listview1.SelectedItems)
{
var lvi = this.listview1.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
var cell = this.GetVisualChild<ContentPresenter>(lvi);
var txt = cell.ContentTemplate.FindName("txtCodCli", cell) as TextBlock;
sb.Append(txt.Text);
//TODO: grab the other column's templated controls here & append text
}
System.Windows.Clipboard.SetData(DataFormats.Text, sb.ToString());
This assumes that in your XAML you have
<TextBlock x:Name="txtCodCli" TextAlignment="Left" Text="{Binding Path=VFT_CLI_CODICE}" />
"Where GetVisualChild T is
public T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
I would think you would have to monitor for SelectionChanged events and then format the items in a particular text format and then utilize the Clipboard.SetText method to set the items into the clipboard.
http://msdn.microsoft.com/en-us/library/system.windows.clipboard.aspx
private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (var item in e.AddedItems.OfType<ListViewItem>())
{
Clipboard.SetText(item.ToString());
}
}
I solved it this way. I have added Ctrl + C event listener and then added logic to copy to clipboard
XAML
<Window
....
Loaded="Window_Loaded"
...>
in code
private void WindowKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.C && Keyboard.Modifiers == ModifierKeys.Control)
{
var sb = new StringBuilder();
var selectedItems = LVLog.SelectedItems;
foreach(var item in selectedItems)
{
sb.Append($"{item.ToString()}\n");
}
Clipboard.SetDataObject(sb.ToString());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With