F#: Add and remove event handlers

天大地大妈咪最大 提交于 2020-01-14 09:48:24

问题


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?


回答1:


As you already mentioned, you need to create an instance of delegate:

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

Then you can use ch as an argument to AddHandler or RemoveHanlder. 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):

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

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

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):

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

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.




回答2:


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)


来源:https://stackoverflow.com/questions/2129661/f-add-and-remove-event-handlers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!