WPF: C# Interoping with F#


Talking to Ody about F#, Akka, and Irrelevant Architects

I’m chopping it up with Ody about F#, Property-based Testing, Akka, etc.

Reactive Programming – 2:52
Akka dot Net – 23:26
Immutable Databases – 37:00
Architects + F# – 47:00
Multi-Threading Discussion – 52:22
Testing Discussion – 58:45
Codebases and Architecture – 1:17:23
Property based Testing – 1:32:33
F# vs C# for User Interfaces – 1:44:00
Motivation for Software Developers – 1:57:20
Is there any need for a Database? – 2:03:00
Architecture – 2:12:00

F# and WPF: The DelegateCommand


This post will provide insight on how to implement the DelegateCommand in F#.

The Delegate Command

The DelegateCommand implements the ICommand interface. This command implementation provides two delegates, Execute and CanExecute.

The following is an implementation of the DelegateCommand:

open System
open System.Windows
open System.Windows.Input
open System.ComponentModel

type DelegateCommand (action:(obj -> unit), canExecute:(obj -> bool)) =
    let event = new DelegateEvent<EventHandler>()
    interface ICommand with
        member this.CanExecuteChanged = event.Publish
        member this.CanExecute arg = canExecute(arg)
        member this.Execute arg = action(arg)

The following code is an example implementation of how the DelegateCommand is used:

member self.Play =
    DelegateCommand ((fun _ -> printf "Hello World"), fun _ -> true) :> ICommand

If you’ve noticed, in order to expose the Execute and CanExecute methods for a client to call, we cast the command to the interface type as shown below:

:> ICommand

Without the cast to ICommand, a client cannot invoke the command because it’s just not exposed within F# at the concrete implementation level.

The XAML would look something like this:

<Button Grid.Row="6" Grid.Column="1" Content="Go!" Command="{Binding Play}" />


In conclusion, I have provided insight on how to implement the DelegateCommand in F#. It is essential to cast an implementation of a DelegateCommand to an ICommand for callers to invoke it.