Responding to a WPF Command from Windows Forms
To allow a Windows Forms control to respond to a WPF command, you must host that control in a WindowsFormHost element in WPF (as described above). The solution described here takes advantage of the CommandBindings
collection of the UIElement class (WindowsFormsHost inherits from UIElement). By creating CommandBindings, you can effectively wire up your Windows Forms control to a given WPF Command.
As with the previous example, it's convenient to use a class (TextboxCommandBridge) to wrap up all this functionality. The example shown here focuses on the Paste
command, but the downloadable code for this article includes implementations for the Cut
commands as well.
The constructor tells most of the story:
TextboxCommandBridge(TextBox textBox, WindowsFormsHost host)
_textBox = textBox;
The constructor adds a CommandBinding to the host of the Windows Forms control. Notice that the constructor of the CommandBinding class accepted delegates for Executed
In the implementation of the Executed
does the heavy lifting:
void PasteCommandExecuted(object sender,
In the CanExecute
delegate, you have to perform some logic to determine whether the user should be able to paste, by calling the PasteCommandCanExecute method
void PasteCommandCanExecute(object sender,
args.CanExecute = !_textBox.ReadOnly
&& _textBox.Enabled &&
At this point, the menu enables only when the TextBox is not read only, is enabled, and the clipboard contains some text to paste.
WPF/Windows Forms Interoperability Limitations
While the interoperability support between WPF and Windows Forms is very powerful, there are a few things that you should avoid. For example, while WPF windows support transparency, Windows Forms controls do not. Also, transformations such as rotation do not work for Windows Forms controls even if they are hosted in WPF.
Another scenario to avoid is overlapping ElementHosts, because the ElementHosts don't interact—they are rendered as separate items.
Finally, focus is handled differently between WPF and Windows Forms. While delving into the details of these differences is beyond the scope of this article, you shouldn't assume that a Windows Forms control placed on a WPF window will behave in exactly the same way in terms of focus.
Despite these minor problems, I hope you've seen that—whether you're building a new WPF project that needs to host some existing Windows Forms controls, or extending a Windows Forms project but want to take advantage of WPF controls—the process for hosting the controls is both similar and reasonably easy to accomplish.