I’m trying to add & remove an event handler from a Silverlight FrameworkElement, but I just can’t get the syntax correct.
I want to do something like this:
let clickedEventHandler = fun args -> printfn "Click!"
fe.MouseLeftButtonDown.AddHandler( clickedEventHandler)
...
fe.MouseLeftButtonDown.RemoveHandler(clickedEventHandler)
What should be the correct way to do this?
As you already mentioned, you need to create an instance of delegate:
Then you can use
chas an argument toAddHandlerorRemoveHanlder. The reason is, that F# function value isn’t actually represented as any delegate type. It has it’s own type, which isn’t a delegate (see also another SO discussion). You can see the difference if you look at the types in F# interactive (or VS IntelliSense):What may be confusing is that F# also allows implicit conversion from lambda function value to a compatible delegate type when calling a method, however this works only when you give a lambda function directly as the argument (I think):
Another reason why you still need delegates in F# is that delegates have a well-defined comparison semantics (they are compared as any other reference types). For functions, the F# specification doesn’t say when they are equal.