This is the example from Foundations of F# that shows how to added and remove event:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#light
open System
open System.Windows.Forms
let form =
    let temp = new Form()
    let stuff _ _ = ignore(MessageBox.Show("This is \"Doing Stuff\""))
    let stuffHandler = new EventHandler(stuff)
    let event = new Button(Text = "Do Stuff", Left = 8, Top = 40, Width = 80)
    event.Click.AddHandler(stuffHandler)
    let eventAdded = ref true
    let label = new Label(Top = 8, Left = 96)
    let setText b = label.Text <- (Printf.sprintf "Event is on: %b" !b)
    setText eventAdded
    let toggle = new Button(Text = "Toggle Event", Left = 8, Top = 8, Width = 80)
    toggle.Click.Add(fun _ ->
        if !eventAdded then
            event.Click.RemoveHandler(stuffHandler)
        else
            event.Click.AddHandler(stuffHandler)
        eventAdded := not !eventAdded
        setText eventAdded)
    let dc c = (c :> Control)
    temp.Controls.AddRange([| dc toggle; dc event; dc label; |]);
    temp
do Application.Run(form)

It doesn't quite meet you needs since the AddHandler function only exists for true .NET events (which are represented in F# by the IDelegateEvent) and not the simpler IEvent interface which is created by filter. This means you'd have to create a IDelegateEvent using create_DelegateEvent. But, unless you plan to publish this event as part of an class interface, it maybe be simpler just to remove the use of IEvent.filter and put this logic in your handler.

By on 1/16/2008 12:15 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper