Saturday, May 26, 2012

MVVM for WindowsForms


Some years ago, I became interest in MVVM for developing WPF (and Silverlight) projects. After much research, I chose Caliburn.Micro: small, simple yet powerfull. I like the convention over configuration approach. In spite of MVVM being accused of making you write more code, Caliburn.Micro's convention over configuration means it has the ability to inject the binding code and makes you write less code. Your view classes have no code behind at all: the .cs file is absent. As Caliburn.Micro injects the InitializeComponent() call you don 't need that file at all. You can't write code behind by mistake if there is no file to do it.

Another nice feature I found in Caliburn.Micro is the implementation of the Screen Activator pattern. You shoudn't open and close views at your will and catch the "isn't saved" issue sometimes and miss it some other times. The “Screen Activator” Pattern is explained by Jeremy Miller. I won't explain it here but it's important to emphasize that it fits the general view separation pattern (MVC, MVP, MVVM).

Recently I was asked to develop something in WindowsForms. It started life as usual WindowsForms projects: event handlers, more event handlers and even more event handlers. It  became obvious something was missing: screen activator pattern for starters and while we are at it, MVVM for WinForms.

I asked Google about it and got no obvious results. I asked two of my techies co-workers if MVVM for WindowsForms was possible. Both gave me the exact same answer: "No way! WindowsForms is missing the rich bindings of WPF and Silverlight (OneTime, OneWay, TwoWay, OnewayToSource) and it is also missing the TypeConverters."

First things first.

  • Screen Activator Pattern for WindowsForms - you can find it here, ported by jagui
  • Rich Bindings and TypeConverters - Truss by Kent Boogaart, does it in an UI independent way
  • Commands - WPF Application Framework (WAF) has a WafWinFormsAdapter project that takes care of some MVVM stuff namely commands


Again, can we have MVVM for WinForms?

Yes we can. We have all the pieces. We just have to glue them together.

Can we port Caliburn.Micro to WindowsForms?

Not yet. Several problems have to be solved first. Remove four references from Caliburn.Micro and you'll see what I mean:
- WindowsBase
- PresentationCore
- PresentationFramework
- System.Windows.Interactivity


The are four bigs issues identified so far:
  1. Get rid of DependencyObject and DependencyProperty that pops a bit everywhere in CM
  2. Replace FrameworkElement and UIElement by WindowsForms objects
  3. Stick to WAF's implementation of Command or replace EventTrigger
  4. Replace DataContext

There are also a lot of small issues that I hope can be solved easily. I'll report back.

1 comment: