Add f # function as an event handler in xaml

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

+5
source share
2 answers

Essentially, you need to download the xaml file and find the 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 just add an event handler:

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

You can get fancy and use top-notch event combiners - here's a great step-by-step introduction:

http://blogs.msdn.com/b/timng/archive/2010/05/06/f-wpf-events.aspx

+1
source

F # ( ), Silverlight . , :

, , XAML ( F # Silverlight, member let).

( ) Silverlight - Silverlight F # # Silverlight. . ( ) :

open System.Windows.Controls

// Dynamic invoke operator that makes accessing XAML elements easy 
// (easier than using 'FindName' explicitly in the code
let (?) (this : Control) (prop : string) : 'T = // '
  this.FindName(prop) :?> 'T // '

type MyControl() as this =
  inherit UserControl()
  do 
    let path = "/MyProject;component/MyControl.xaml"
    let uri = new System.Uri(path, UriKind.Relative)
    Application.LoadComponent(this, uri)

    // Get Button named 'TestButton' from the XAML file
    let btn : Button = this?TestButton
    // Add event handler to the button
    btn.Add(fun _ -> btn.Text <- "Clicked!")
+2

All Articles