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.

[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

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

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

Please submit your question and answer.