Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F#/WPF event binding

Tags:

wpf

f#

I am wandering if there is a way of hooking an event defined in XAML to a F# function of member ? Of course, I could do it diagrammatically but it is kind of inconvenient.

like image 351
user503775 Avatar asked Dec 04 '22 10:12

user503775


1 Answers

I suppose the question is whether you can specify F# member as an event handler using XAML markup:

<Button x:Name="btnClick" Content="Click!" Click="button1_Click" />

As far as I know, the answer is No.

The way this works in C# is that the registration of event handler is done in C# code (partial class) generated by the designer (you can see that in the obj directory in files named e.g. MainForm.g.cs). F# doesn't have any direct support for WPF designer, so it cannot generate this for you. You'll have to write the code to attach event handlers by hand (but that's quite easy).

I have some examples in my London talk about Silverlight. You can implement the ? operator to get nice access to the XAML elements:

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

   // Get button using dynamic access and register handler
   let btn : Button = this?btnClick
   do btnClick.Click.Add(fun _ -> (* ... *))

The ? operator declaration that I used is:

let (?) (this : Control) (prop : string) : 'T = // '
  this.FindName(prop) :?> 'T
like image 75
Tomas Petricek Avatar answered Jan 01 '23 21:01

Tomas Petricek