Live Chat Icon For mobile
Live Chat Icon

How do I copy the contents of multiple selected items of a ListBox so that they fall in different lines in Excel and Notepad when pasted?

Platform: WPF| Category: ListBox

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.

<ListBox x:Name='myListBox' SelectionMode='Multiple'>   

In your code behind:

        public Window1()     
            CommandBinding cb = new CommandBinding(ApplicationCommands.Copy, CopyCmdExecuted, CopyCmdCanExecute);   
        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;   
        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;   
                e.CanExecute = false;   

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.