Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / F#

FsViewModelBase

5.00/5 (1 vote)
3 Sep 2016CPOL 7.2K  
F# Quotations support for ViewModelSupport.ViewModelBase Property getset Accessors

Background

I recently used ViewModelBase in an MVVM application with F#.

The following code is a simple subclass of ViewModelSupport.ViewModelBase that implements support for using F# Quotations as property get\set accessors.

Using the Code

Reference either ViewModelSupport.dll or ViewModelSupport_SL.dll and add the following to your project:

F#
type FsViewModelBase() =
    inherit ViewModelSupport.ViewModelBase()
    // requires ViewModelSupport.dll or ViewModelSupport_SL.dll
    // from http://viewmodelsupport.codeplex.com/
    let getPropertyName = function 
        | Microsoft.FSharp.Quotations.Patterns.PropertyGet(_,pi,_) -> pi.Name
        | _ -> invalidOp "Expecting property getter expression"
    member this.FGet<'T>(quot:Quotations.Expr<'T>, ?defaultValue:'T) =
        match defaultValue.IsSome with
            | true -> this.Get<'T>(quot |> getPropertyName, defaultValue.Value)
            | false -> this.Get<'T>(quot |> getPropertyName)
    member this.FSet<'T>(quot:Quotations.Expr<'T>, 
    value:'T) = this.Set(quot |> getPropertyName, value)

Now you can implement F# quotations in your derived classes, like so:

F#
type myObservableScore() =
    inherit FsViewModelBase()

    member this.Score
        with get() = this.FGet(<@ this.Score @>, 0)
        and set (value) = this.FSet(<@ this.Score @>, value)

(Note: I named these methods "FGet" and "FSet" because naming them "Get" and "Set" causes a duplicate Key exception on base initialization of `inherit ViewModelSupport.ViewModelBase()` at runtime.)

History

  • 9/3/2016 01:26 - Initial post
  • 9/3/2016 11:17 - Minor updates, additional description

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)