This is a quick post demonstrating how to create WPF Dependency Properties in F#. There is a bit of a trick to it as you have to use the val keyword to define a field and that field must be mutable and you also have to use explicit interface access.
An example is easier than an explanation!
open System.Windows open System.Windows.Controls type CustomControl() = inherit FrameworkElement() [<DefaultValue(false)>] static val mutable OrientationProperty:DependencyProperty static do (CustomControl.OrientationProperty <- DependencyProperty.Register ("Orientation", typeof<Orientation>, typeof<CustomControl>, new FrameworkPropertyMetadata(Orientation.Horizontal))) let toDep x = x :> DependencyObject member self.Orientation with get() = (self |> toDep).GetValue(Axis.OrientationProperty) :?> Orientation and set (x:Orientation) = (self |> toDep).SetValue(Axis.OrientationProperty, x)
The key considerations are as follows:
- The static field for the dependency property must be declared as static val mutable and must also have the DefaultValue attribute. The attribute has the argument false because the value will be created by the static constructor rather than as a default value
- The initialization of the static property is wrapped in parentheses because otherwise the F# syntax is incorrect
- Because access of the GetValue and SetValue methods use the DependencyObject class methods, it is necessary to cast the instance object to DependencyObject (a little F# semantic), and so toDep is a helper function for that purpose
- In other .NET languages you need to cast the result of GetValue and the same is true here, but because it is a runtime cast you need the dynamic operator “:?>” and not the static one “:>”
The following links have more information about dependency properties:
- MSDN documentation: http://msdn.microsoft.com/en-us/library/ms752914.aspx
- WPF Tutorial: http://www.wpftutorial.net/DependencyProperties.html
You may also find the F# specification (section 8.5.4) useful if you want to know more about creating interoperable class fields (as opposed to methods and properties).