F#/WPF event binding

后端 未结 4 1617
青春惊慌失措
青春惊慌失措 2020-12-29 16:48

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. <

4条回答
  •  我在风中等你
    2020-12-29 17:29

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

    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
    

提交回复
热议问题