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<string>(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 <- v
             event.Trigger(this, new PropertyChangedEventArgs("Name"))

   //Definition of the "SearchCommand"
   member this.SearchCommand
        with get() = searchCommand

Cool, don’t you love this F# syntax? It’s so readable :)

Now we are ready to bind the MainPageVM to a xaml view inserting this simple code:

<StackPanel Orientation="Vertical">
     <!-- Example of binding to a F# ViewModel Command -->
     <Button Height="40" Content="Click me!"
           cmd:Click.Command="{Binding SearchCommand}"
           cmd:Click.CommandParameter="Hello from a ViewModel F# Command parameter"/>

     <!-- Example of binding to a F# ViewModel property -->
     <TextBlock Text="{Binding Name}" Height="40"/>
</StackPanel>

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!!


4 Responses to “Silverlight and ViewModel meet F#”

Leave a Reply