Search code examples
silverlighteventsxamlf#

Add f# function as event handler in xaml


Does anyone know how to add an F# event handler to a control in the xaml file?


Solution

  • Essentially you need to load a xaml file and find a control by name:

    let w = Application.LoadComponent(new  System.Uri(
              "/twitterstream;component/Window.xaml", System.UriKind.Relative
            )) :?> Window
    let b = w.FindName("buttonToggle") :?> Button
    

    and then you can simple add a handler an event:

    b.Click.Add(fun _ -> ...)
    

    You can get fancy and use first-class event combinators - here is a great step-by-step introduction:

    Link