This is the second part of my series on using MVVM with WPF. In the first article I discussed architecting disconnected applications and how MVVM was a great fit for WPF smart clients as well as Silverlight web clients. Now we move on to the process of refactoring an old Windows Forms application to use this new architecture.
The main concern with changing an underlying technology is the initial investment in rewriting code. To help mitigate this issue, WPF has provided a WindowsFormsHost element that allows us to host WinForms controls inside of a WPF Page. Obviously this limits how effectively we can leverage other features provided by WPF, however with a few workarounds it's a viable solution to avoid having to completely rewrite those old WinForms controls.
How easy is it to implement the WindowsFormsHost?
Okay, it's only slightly more complicated than that. You will need to add add a reference to WindowsFormIntegration and possibly System.Windows.Forms (if it is not already referenced).
Now the question comes to how we interact with this control from our ViewModel since we can't use WPF bindings in our WinForms control. We can bridge this gap by adding events to our WinForms user control.
Then we wire up the events to our DataContext in our WPF Page code-behind.
While I generally prefer to avoid using the code-behind, we also don't want our ViewModel to be aware of the internal workings of our View.
The end result is our Windows Forms control interacts with elements in our WPF Page.
Download Demo Source Code