Silverlight and ViewModel meet F#

Many MVVM implementations are available on the net, personally I love the approach used by Laurent Bugnion in the MVVM Light toolkit and Michael Sync in the Silverlight MVVM toolkit (Jeremiah Morril have posted a great article about this pattern, don’t forget to read it here).

All these examples use C#, what about F# for describing ViewModel classes? F# is a very powerful and readable language and permits to perform operations using a small amount of code. Last, but not least, at this time it’s a first citizen .NET language and can be easily used in Silverlight applications as well.

How can we build a Silverlight MVVM solution using F#?

First of all, download and install the F# for Silverlight templates and samples.

Let’s start by defining a simple F# ViewModel class containing a simple “Name” property and a “SearchCommand”, this one using the DelegateCommand implementation available in Prism:

namespace SilverlightViewModelFSharp.ViewModels

open System.ComponentModel
open Microsoft.Practices.Composite.Presentation.Commands;
open System.Windows

type MainPageVM() =

   //Definition of the PropertyChanged event
   let event = Event<PropertyChangedEventHandler, PropertyChangedEventArgs>()

   //Definition of the "name" property
   let mutable name = "This is the value of a property defined in the F# ViewModel"

   //Definition of a test Command
   let searchCommand = new DelegateCommand(fun (x) -> MessageBox.Show(x) |> ignore )

   //INotifyPropertyChanged interface
   interface INotifyPropertyChanged with
      member this.add_PropertyChanged(e) = event.Publish.AddHandler(e)
      member this.remove_PropertyChanged(e) = event.Publish.RemoveHandler(e)

   //Definition of the "Name" property
   member this.Name
        with get() = name
        and  set(v) =
             name</pre>
Cool, don’t you love this F# syntax? It’s so readable 🙂
<p align="justify">Now we are ready to bind the MainPageVM to a xaml view inserting this simple code:</p>

<pre>

     <!-- Example of binding to a F# ViewModel Command -->
     <button></button>

     <!-- Example of binding to a F# ViewModel property -->
     

To make the ViewModel magic work, just assign the MainPageView DataContext with the F# ViewModel:

public MainPageView()
   {
       InitializeComponent();
       this.DataContext = new MainPageVM();
   }

The source code is available for download here.

New: updated the source code for Visual Studio 2010 Beta 2.

Happy Silverlighting!!