Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable paste using CTRL+V in empty listbox?

Tags:

c#

wpf

c#-3.0

I have an empty listbox which I would like to allow the user to paste items into. Currently I make sure the listbox has focus (as per WPF: How to enable a Command?) when the user clicks on it. Then if they right-click the context menu which contains the Paste command will be enabled and can be clicked which is excellent. However if instead of right-clicking the user presses CTRL+V on the keyboard the Paste command does not execute.

So far I can't figure out how to make this work. If the listbox has items in it and one of them is selected everything works fine.

Thanks

like image 602
Chris Daviduik Avatar asked Apr 19 '26 21:04

Chris Daviduik


2 Answers

Add your own CommandBinding for the Paste-Command to the ListBox.

m_yourlistBoxReference.CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste,YourExecutedHandler,YourCanExecuteHandler));

However, such as you already wrote, you have to ensure that the ListBox is focused, otherwise the CommandBinding will not execute. To ensure this, you can register to the PreviewMouseDown-event and focus the ListBox if not already IsFocused is true.

like image 59
HCL Avatar answered Apr 21 '26 10:04

HCL


I'm not a WPF expert; however, in WinForms the easiest way is to add a context menu with the short-cut keys for Cut, Copy, Paste, etc. Then you don't have to do anything but implement the context menu click.

like image 31
csharptest.net Avatar answered Apr 21 '26 09:04

csharptest.net