有人知道如何在xaml文件中为控件添加F#事件处理程序吗?
member
而不是let
函数)。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!")
基本上,您需要加载一个XAML文件并按名称查找控件:
let w = Application.LoadComponent(new System.Uri(
"/twitterstream;component/Window.xaml", System.UriKind.Relative
)) :?> Window
let b = w.FindName("buttonToggle") :?> Button
然后你可以简单地添加一个事件处理程序:
b.Click.Add(fun _ -> ...)
你可以使用高级事件组合器 - 这里有一个很棒的逐步介绍: