Click here to Skip to main content
15,886,362 members
Articles / Programming Languages / F#
Tip/Trick

FsViewModelBase

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
3 Sep 2016CPOL 7K  
F# Quotations support for ViewModelSupport.ViewModelBase Property get\set 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)


Written By
Software Developer Vivrant
United States United States
Software developer working with Emergency Medical Services (EMS), Emergency Response Services (ERS), Ambulance Billing, Computer-Aided Dispatch (CAD), Cloud-Based solutions and Cost-Recovery for First-Responders.

Comments and Discussions

 
-- There are no messages in this forum --