What is the best way to deal with the same shortcut in WPF and WinForms controls?

I have a WPF application with the following KeyBinding in the main window:

<KeyBinding Command="Commands:EditCommands.Undo" Gesture="CTRL+Z" /> <KeyBinding Command="Commands:EditCommands.Redo" Gesture="CTRL+Y" /> 

This forces the command to respond to the shortcut label. However, in all places where I inserted WinForms text fields or text fields, I lost the ability to use these shortcuts. If I remove the above bindings, WinForms shortcuts work fine.

How can I support these shortcuts in both WinForms and WPF? I would prefer to use the general method, as this problem can affect many other teams with the same keywords.

+4
source share
1 answer

I am puzzled by why you are not using built-in commands:

  • ApplicationCommands.Undo and
  • ApplicationCommands.Redo

There are several advantages to using these built-in commands:

  • Their key bindings are automatically set based on the locale ( Ctrl + Z and Ctrl + Y cannot be standard undo / redo keys in all locales)
  • They comply with TextBox and RichTextBox
  • They cross the border of WPF ↔ WinForms without any problems.
  • They work with accessibility interfaces.
  • They are called by the built-in "cancel" keys on keyboards that have them

Therefore, if possible, you should use the built-in ApplicationCommands by simply registering CommandBindings for them in the appropriate places in your code.

Additional Information

If you use the built-in undo / redo functions in WPF and WinForms, this just works. For example, the following creates two RichTextBoxes , one based on WinForms and one on WPF, and both have full undo / redo capabilities:

 <UniformGrid Columns="2" xmlns:winforms= "clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"> <WindowsFormsHost > <winforms:RichTextBox /> </WindowsFormsHost> <RichTextBox /> </UniformGrid> 

Since this works, and yours does not, try to find out what is different. You said in your comments that you tried to remove custom WPF InputBindings . Have you done the same on the WinForms side? If not, try, or if this is not possible, edit your question to show this code.

Note that you can reassign ApplicationCommands to your own RoutedCommands : just add a CommandBinding and in the handler run your own RoutedCommand .

+2
source

Source: https://habr.com/ru/post/1312802/


All Articles