You can do this easily by extending the ApplicationCommands.Copy command as follows:
See this forum for better formatting of the code ListView Copy to clipboard selected row.
[XAML]
<ListBox x:Name='myListBox' SelectionMode='Multiple'>
<ListBox.Items>
<ListBoxItem>Item1</ListBoxItem>
<ListBoxItem>Item2</ListBoxItem>
<ListBoxItem>Item3</ListBoxItem>
<ListBoxItem>Item4</ListBoxItem>
</ListBox.Items>
</ListBox>
In your code behind:
[C#]
public Window1()
{
this.InitializeComponent();
CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, CopyCmdExecuted, CopyCmdCanExecute);
this.myListBox.CommandBindings.Add(cb);
}
void CopyCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
ListBox lb = e.OriginalSource as ListBox;
string copyContent = String.Empty;
// The SelectedItems could be ListBoxItem instances or data bound objects depending on how you populate the ListBox.
foreach (ListBoxItem item in lb.SelectedItems)
{
copyContent += item.Content.ToString();
// Add a NewLine for carriage return
copyContent += Environment.NewLine;
}
Clipboard.SetText(copyContent);
}
void CopyCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
ListBox lb = e.OriginalSource as ListBox;
// CanExecute only if there is one or more selected Item.
if (lb.SelectedItems.Count > 0)
e.CanExecute = true;
else
e.CanExecute = false;
}
Share with