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:
type FsViewModelBase() =
inherit ViewModelSupport.ViewModelBase()
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:
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