Tuesday, September 6, 2011

WPF/SilverLight F# Converter

Since 2006 I started to develop WPF application, I experienced the pain of writing XAML, binding, converter, coerce, and the MVVM pattern. I find the F# is the best tool to write converters. I can still recall somebody was trying to write some framework to chain some multiple converters. I published a snippet on http://fssnip.net/7Q.

First of all, let me justify converter is still useful when MVVM pattern is available. First application of converter is for graphic designers. The converter provide graphic designer some basic mathematically tool to design a control. The MVVM pattern is too much for a graphic designer. Secondly, the MVVM itself can use converter as well. The last point is how big is your project. I would not say MVVM pattern is suitable for a small demo project. Use the right tool at the right time to do the right job is the key.

The converter snippet design idea is simple. It groups the functions into a module and function composition and pipeline can chain different function and form a new function. The converter basically is a function, you can use strategy pattern (http://fssnip.net/7k) as the starting point to design a converter.

The hard part is how to make your function look like (object, type, object, cultureInfo) format. The following function is the function to convert your function to (object, type, object,cultureInfo) signature.


let convert<'T> f (obj:System.Object) (t:Type) (para:System.Object) (culture:Globalization.CultureInfo)  = (obj :?> 'T) |> f |> box
The concrete implementation is to chain up different function to form a string to visibility as convert function and nullFunction as convertBack function. The converter is trying to reduce the coding effort and make sure the generated code can work with Blend. I added another converter which I used a lot in my data binding debugging. The converter itself does not do anything, but can be used to check if the binding actually work or not.

No comments: