How to write type constraint for a event member?

138 views Asked by At

WPF controls have many event members which has a same name without sharing the same interface or the base class. F#'s type constraint enables writing function which works on all the objects which has the same member. Then, if I can write type constraint for a event member, I can write curried function witch facilitates property setting in the same way for many controls.

open System.Windows.Controls
let inline click handler control =
  (^T:(member Click:IEvent<_,_>)control)
    .Add handler

Button()
|> click (fun _ -> ()) // error!

MenuItem()
|> click (fun _ -> ()) // error!

type A () =
  [<CLIEvent>]
  member __.Click = Event<_>().Publish
A() |> click (fun _ -> ()) // It works! but IntelliSense shows the member as "event A.Click .."

But the above code doesn't works.. I guess writing type constraint for event member is impossible.. Because it's a small problem and if we solve every small problems by language features, the language would become so complex as no one can use! (now F# seems powerful and simple)

Then I want to know some alternative way to solve this probrem, if it exists.

1

There are 1 answers

0
nagat01 On

I solved it myself after post this question. You can access event member by calling method add_* and remove_*. And type constraint works with the method calling. Thanks!

let inline click handler control =
  let handler = RoutedEventHandler(fun _ e -> handler e)
  (^T:(member add_Click:RoutedEventHandler->unit)control,handler)

Button() |> click (fun _ -> ()) // works!
MenuItem() |> click (fun _ -> ()) // works!