F# and WPF: The DelegateCommand

Intro

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
        [<CLIEvent>]
        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}" />

Conclusion

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: