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
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.
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.
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