F #: adding and removing event handlers

I am trying to add and remove an event handler from Silverlight FrameworkElement, but I just cannot get the syntax correctly.

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 right way to do this?

+4
source share
2 answers

As you mentioned, you need to instantiate a delegate:

 let ch = new MouseButtonEventHandler(fun obj args -> printfn "Click!") 

You can then use ch as an argument to AddHandler or RemoveHanlder . The reason is that the value of the F # function is not actually represented as any type of delegate. It has its own type, which is not a delegate (see also another discussion of SO ). You can see the difference if you look at the types in F # interactive (or VS IntelliSense):

 > (fun (o:obj) (a:MouseButtonEventArgs) -> printfn "Click!") val it : obj -> MouseButtonEventArgs -> unit = (...) > new MouseButtonEventHandler(fun oa -> printfn "Click!") val it : MouseButtonEventHandler = (...) 

What can be confusing is that F # also allows you to implicitly convert the value of the lambda function to a compatible delegate type when calling the method, however this only works when you give the lambda function directly as an argument (I think):

 fe.MouseLeftButtonDown.AddHandler(fun obj args -> printfn "Click!") 

Another reason you still need delegates in F # is because delegates have well-defined comparison semantics (they are compared like any other reference types). For functions, the F # specification does not say when they are equal.

+5
source

In this case, it turns out you can do the following:

 let clickedEventHandler = new MouseButtonEventHandler(fun obj args -> printfn "Click!") fe.MouseLeftButtonDown.AddHandler( clickedEventHandler) ... fe.MouseLeftButtonDown.RemoveHandler(clickedEventHandler) 
+2
source

Source: https://habr.com/ru/post/1299285/


All Articles